Programmers | 다음 큰 숫자 [LV2] (Java)

문제

풀이 1 : bitCount() 활용

Integer.bitCount는 정수를 매개변수로 넣었을 때 그 정수의 이진수에서 1의 개수를 반환한다.

1111 -> 4

public class Solution {
    public int solution(int n) {
        int cnt = Integer.bitCount(n);
        for(int i = n+1; ; i++){
            if (Integer.bitCount(i) == cnt) return i;
        }
    }
}

풀이 2 : bitCount() 대신 함수 구현

비트 연산을 통해 문제를 해결했다.
&, >> 연산자..

public class Solution {
    public int solution(int n) {
        int count = countOne(n);         
        for(int i = n+1; ; i++){
            if(countOne(i) == count) return i;
        }
    }

    public int countOne(int n) {
        int cnt = 0;
        while(n>0) {
            if((n&1) == 1) cnt++;
            n >>= 1;
        }
        return cnt;
    }
}

풀이 3 : 이진수 구하기

public class Solution {
    public int solution(int n){
        int count = countOne(n);
        while(countOne(++n) != count);
        return n;
    }
    private int countOne(int n) {
        String bin = Integer.toBinaryString(n);
        int count = 0;
        // 1번
        for (int i = 0; i < bin.length(); i++) {
            String b = bin.substring(i, i+1);
            if (b.equals("1")) count++;
        }
        // 2번
        // for(char ch : bin.toCharArray()) {
        //     if(ch == '1') count++;
        // }
        return count;
    }
}

좋은 웹페이지 즐겨찾기