티스토리 뷰

728x90
 

코딩테스트 연습 - 다음 큰 숫자

자연수 n이 주어졌을 때, n의 다음 큰 숫자는 다음과 같이 정의 합니다. 조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다. 조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니

programmers.co.kr

//다른사람코드
public int solution2(int n) {
    int answer = Integer.bitCount(n);

    while(true) {
        n++;
        if(answer == Integer.bitCount(n) ) {
            answer = n;
            break;
        }
    }
    return answer;
}

public int solution(int n) {
    int answer = 0;
    String binary = Integer.toBinaryString(n);
    int cnt = 0;
    for (int i = 0; i < binary.length(); i++) {
        if (binary.charAt(i) == '1') {
            cnt++;
        }
    }
    String tempStr = "";
    while (true) {
        n++;
        int tempCnt = 0;
        tempStr = Integer.toBinaryString(n);
        for (int i = 0; i < tempStr.length(); i++) {
            if (tempStr.charAt(i) == '1') {
                tempCnt++;
            }
        }
        if (cnt == tempCnt) {
            break;
        }
    }
    answer = Integer.parseInt(tempStr, 2);
    return answer;
}

이진수 변환 함수

Integer.toBinaryString(n)

이진수에서 1의 개수를 세어주는 함수

Integer.bitCount(n);

 

내부 코드

@HotSpotIntrinsicCandidate
public static int bitCount(int i) {
    // HD, Figure 5-2
    i = i - ((i >>> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    i = (i + (i >>> 4)) & 0x0f0f0f0f;
    i = i + (i >>> 8);
    i = i + (i >>> 16);
    return i & 0x3f;
}
댓글
최근에 달린 댓글
최근에 올라온 글
Total
Today
Yesterday
«   2025/10   »
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
26 27 28 29 30 31