본문 바로가기

알고리즘 문제풀이

[프로그래머스 12911] Level2 다음 큰 숫자(Java)

문제 URL

https://school.programmers.co.kr/learn/courses/30/lessons/12911

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제풀이 Key Point

  • 2진수로 변환한 숫자의 1의 갯수가 같아야한다.
    • 간단한 문제였는데 처음에는 비트연산이며 이것저것 너무 복잡하게 생각해서 시간을 많이 소비한 것 같다. 😥

 

Java 문제풀이

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
class Solution {
    public int solution(int n) {
        int answer = 0;
        
        String nToBinary = Integer.toBinaryString(n);
        int oneCountByN = calculateOneCount(nToBinary);
        int oneCountByBigN = 0;
        while (oneCountByN != oneCountByBigN) {
            n++;
            oneCountByBigN = calculateOneCount(Integer.toBinaryString(n));
            
            if (oneCountByN == oneCountByBigN) {
                answer = n;
            }
        }
        
        return answer;
    }
    
    private int calculateOneCount(String binaryNumber) {
        int oneCount = 0;
        for (int i = 0; i < binaryNumber.length(); i++) {
            if (binaryNumber.charAt(i) == '1') {
                oneCount++;
            }
        }
        
        return oneCount;
    }
}
 
cs