<나의풀이>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Solution { public int solution(int n) { int answer = 0; String s = Integer.toBinaryString(n); int cnt=0; for(int i=0; i<s.length(); i++){ if(s.charAt(i)=='1') cnt++; } while(true){ String ss = Integer.toBinaryString(++n); int cnt1=0; for(int i=0; i<ss.length(); i++){ if(ss.charAt(i)=='1') cnt1++; } if(cnt==cnt1) return n; } } } | cs |
<다른사람풀이>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import java.lang.Integer; class TryHelloWorld { public int nextBigNumber(int n) { int a = Integer.bitCount(n); int compare = n+1; while(true) { if(Integer.bitCount(compare)==a) break; compare++; } return compare; } public static void main(String[] args) { TryHelloWorld test = new TryHelloWorld(); int n = 78; System.out.println(test.nextBigNumber(n)); } } | cs |
bitCount()를 이용한 풀이. bitCount(num)은 num을 비트 즉, 2진법으로 변환 했을때 1의 개수를 리턴해주는 함수이다.