Algorithm

[프로그래머스] 다음 큰 숫자 - JAVA

로넌 2023. 1. 31. 12:18
📌문제

 

💡 풀이

이진법 변환에 대해서 알고있는지 묻는 문제라고 생각했고, Integer.toBinaryString()을 사용해서 풀어야한다는 생각까지하고 문제를 풀고자 하였다.

 

class Solution{
	public int solution(int n){
    	int answer = 0;
        
        // 1. 주어진 n을 2진수로 변환한다.
        String str = Integer.toBinaryString(n);
        
        // 2. 2진수로 변환한 n에 1의 개수를 구한다.
        int cnt = 0;
        
        for(int i=0; i<str.length(); i++){
        	if(str.charAt(i) == '1') cnt++;
        }
        
        // 3. n 다음수부터 반복문을 돌리며 1의 개수가 같은 수를 찾는다.
        
        for(int i=n+1; i<=1000000; i++){
        	String tmp = Integer.toBinaryString(i);
            
            for(int j=0; j<tmp.length(); j++){
            	int tmpCnt = 0;
                if(tmp.charAt(j) == '1') tmpCnt++;
                
            }
            
            if(cnt == tmpCnt){
            	answer = i;
                break;
            }   
        
        }
        
        
        return answer;
    }
}

 

💡 다른 풀이

1의 개수를 반복문을 돌리지 않아도 구할 수 있는 Integer.bitCount() 라는 메소드가 있었다. 

위와 풀이는 비슷하나 훨씬 간결해진걸 확인 할 수 있었다.

class Solution{

	public int solution(int n){
    
    	int answer = 0;
        int cnt = Integer.bitCount(n);
        int tmpCnt = 0;
        
        while(true){
            n++;
            int tmpCnt = Integer.bitCount(n);
            if(cnt == tmpCnt){
            	answer = n;
                break;
            }
        
        }
        
        return answer;
    
    }
}

 

추가

1) 10진수를 2진수, 8진수, 16진수로 변환하기

10진수 -> 2진수 Integer.toBinaryString()
10진수 -> 8진수 Integer.toOctalString()
10진수 -> 16진수 Integer.toHexaString()

 

2) 2진수, 8진수, 16진수를 10진수로 변환하기

2진수 -> 10진수 parseInt(str, 2)
8진수 -> 10진수 parseInt(str, 8)
16진수 -> 10진수 parseInt(str, 16)