1. 문제

2. 나의 풀이

처음에는 직접 binaryNumber를 구하는 메소드와 binary로 변환했을 때 1의 갯수를 구하는 메소드를 짰는데 효율성 테스트에서 실패하였다.

 

찾아보니까 Integer를 binaryString으로 바꿔주는 메소드와 Integer에서 2진수로 변환했을 때 1의 개수를 반환해주는 메소드가 있었다. 해당 메소드를 사용하니 효율성 테스트를 통과할 수 있었다. binaryString으로 바꾸는 부분의 경우 구현을 살펴보니 비트 단위로 조작하는 부분이 있었다. 이 부분은 좀 더 찾아봐야할꺼 같다.

  • Integer.toBinaryString(n);
  • Integer.bitCount(n);
class Solution {
    
    public int solution(int n) {
        int answer = 0;
        
        String binaryNumber = Integer.toBinaryString(n);
        int oneCount = Integer.bitCount(n);
        
        while(true){
            n++;
            int curOneCount = Integer.bitCount(n);
            if(curOneCount == oneCount) {
                answer = n;
                break;
            }
        }

        return answer;
    }
    
    private int getCount(String binaryNumber) {
        int count = 0;
        for(int i=0;i<binaryNumber.length();i++){
            if(binaryNumber.charAt(i) == '1'){
                count++;
            }
        }
        return count;
    }
    
}
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기