Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions counting-bits/rivkode.java
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자바에 toBinaryString 같은 함수가 존재하는지 몰랐네요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
입력받은 n에 대해 toBinaryString() 을 사용하여 binaryString 값을 알아낸뒤 charAt()으로 각 인덱스별 접근하여 1의 개수를 찾아내는 방식이다.
*/

class Solution {
public int[] countBits(int n) {
int[] answer = new int[n + 1];
for (int i=0; i<n+1; i++) {
String bit = Integer.toBinaryString(i);
System.out.println(bit);
int cnt = 0;
for (int j=0; j < bit.length(); j++) {
char c = bit.charAt(j);
int num = c-'0';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 코드가 어떤 역할을 하는 건지 궁금해요. 무작정 2로 나눠서 몫과 나머지를 통해 답을 도출한다는 생각만 했더니...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

안녕하세요 ㅎㅎ 아스키 코드를 사용하였습니다. 여기서 char c 는 숫자형태의 char 를 기대하고 있습니다. 그러므로 '0' 을 빼주게 되면 십진법의 Int 숫자가 반환되게 됩니다. 사실 십진법에 해당하는 48을 빼주어도 되는데 '0' 을 빼주는게 더 직관적이라 보통 숫자연산을 할때 저는 '0' 을 빼줍니다. 그러면 원하는 숫자 int 값을 얻을 수 있게 되어서요.

if (num == 1) {
cnt += 1;
}
}

answer[i] = cnt;
}

return answer;
}
}