Coding test

다음 큰 숫자

본명은이점례 2021. 7. 4. 23:09
728x90

import java.util.*;
import java.math.*;

class Solution {
    public int solution(int n) {
        int onecnt = 0;
        String binary = Integer.toBinaryString(n);
        char [] arr = binary.toCharArray();
        for(char a : arr)
        {
            if(a=='1')
                onecnt++;
        }
        
        int another_onecnt = 0;
        
       while(true) 
        {
            String binary2 = Integer.toBinaryString(n+1);  
            char [] arr2 = binary2.toCharArray();

            for(char a : arr2)
            {
                if(a=='1')
                    another_onecnt++;

            }
            
            if(another_onecnt == onecnt)
                break;
            
            another_onecnt =0;
            n++;
        }
        
        
        return n+1;
    }
}

 


Integer.toBinaryString(n) 이라는 이진수를 String 타입으로 변환해주는 라이브러리를 사용했다.

 

 

다른 사람의 풀이

 

Integer.bitCount 하면 2진수에서 1의 개수를 반환해주는 듯 하다.

728x90