250x250
반응형
Recent Posts
Recent Comments
Link
«   2024/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
Archives
Today
Total
관리 메뉴

재 현

다음 큰 숫자 본문

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

'Coding test' 카테고리의 다른 글

짝지어 제거하기  (0) 2021.09.13
큰 수 만들기  (0) 2021.07.06
H-index  (0) 2021.07.01
N개의 최소공배수  (0) 2021.06.29
숫자의 표현  (0) 2021.06.29