본문 바로가기
백준 Algorithm

[프로그래머스] 다음 큰 숫자 Java 풀이

by Echung 2023. 4. 5.

Problem

다음 큰 숫자

 

Solution

 주어진 조건을 만족하는 큰 숫자를 구하면 되는 문제이다.

1. 기존에 주어진 숫자를 Integer.toBinaryString() 함수를 사용해서 2진법으로 만든다.

2. 2진법에서 1의 숫자를 카운트한다.

3. 주어진 숫자를 ++하면서 위의 1,2번 방법을 반복하면서 1의 숫자가 같은 값을 찾는다.

4. 조건을 만족하는 값을 출력한다.

 

class Solution {
    public int solution(int n) {
        int answer = 0;
        // 10진법을 2진법으로 만듬 
        String str = Integer.toBinaryString(n);
        int count = 0;
        
        // 주어진 조건의 1의 갯수를 카운트한다
        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == '1') count++;
        }
        
        while(true) {
            String temp = Integer.toBinaryString(++n);
            int tempCount = 0;
            
            for(int i = 0; i < temp.length(); i++) {
                if(temp.charAt(i) == '1') tempCount++;
            }
            
            if(count == tempCount) {
                answer = n;
                break;
            }
        }
        
        return answer;
    }
}

사진 1. 실행 결과

 

마치며

 간단한 문제이면서 Integer.toBinaryString() 함수를 알면 풀기 쉬운 문제였다. 다른 사람의 코드를 보면 Integer.bitCount()라는 이진수에서 1의 개수를 세어주는 함수를 사용해서 바로 1의 개수를 파악하는 방법도 있었다. 향후 이런 문제를 만나면 Integer.bitCount()를 사용해서 풀어보도록 해야겠다. 

반응형