알고리즘

<Programmers> 다음 큰 숫자

koyuchang 2020. 4. 28. 11:52

[내 코딩]

class Solution {
  public int solution(int n) {
      int answer = 0;
      int cnt = 0;
        int comCnt =0;

        String nBin = Integer.toBinaryString(n);
        for (int i = 0; i < nBin.length(); i++) {
            if (nBin.charAt(i) == '1') {
                cnt++;
            }
        }
        int temp = n+1;
        while (true) {
            String tmp = Integer.toBinaryString(temp);
            for(int i =0;i<tmp.length();i++){
                if(tmp.charAt(i)=='1'){
                    comCnt++;
                }
            }
            if(cnt==comCnt){
                answer = temp;
                break;
            }
            else{
                temp+=1;
                comCnt=0;
            }
        }
      return answer;
  }
}

 

 

[참조 후 개선된 코드]

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