[코딩테스트 연습] 다음 큰 숫자(Level-2)

Posted by 김성철

코딩테스트 - 다음 큰 숫자

문제 설명
자연수 n이 주어졌을 때, n의 다음 큰 숫자는 다음과 같이 정의 합니다.

조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다.
조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니다.
조건 3. n의 다음 큰 숫자는 조건 1, 2를 만족하는 수 중 가장 작은 수 입니다.
예를 들어서 78(1001110)의 다음 큰 숫자는 83(1010011)입니다.

자연수 n이 매개변수로 주어질 때, n의 다음 큰 숫자를 return 하는 solution 함수를 완성해주세요.

제한 사항
n은 1,000,000 이하의 자연수 입니다.
입출력 예
n result
78 83
15 23
입출력 예 설명
입출력 예##1
문제 예시와 같습니다.
입출력 예##2
15(1111)의 다음 큰 숫자는 23(10111)입니다.

======================================================================================================
class Solution {
public int solution(int n) {
int answer=0;
int oneCount = Integer.bitCount(n);

    while(true){  
        n++;  
        int tempOneCount = Integer.bitCount(n);  
        if(oneCount==tempOneCount){  
            answer=n;  
            break;  
        }  
  
    }  
  
    return answer;  
}   }  

효율성 실패

class Solution {
public int solution(int n) {
int answer=0;
String binary = Integer.toBinaryString(n);
binary = binary.replaceAll(“0”,””);
int oneCount = binary.length();

    while(true){  
        n++;  
        String tempBinary = Integer.toBinaryString(n);  
        tempBinary = tempBinary.replaceAll("0","");  
        int tempOneCount = tempBinary.length();  
        if(oneCount==tempOneCount){  
            answer=n;  
            break;  
        }  
  
    }  
  
    return answer;  
}   }  

효율성 실패

class Solution {
public int solution(int n) {
int addN = n+1;
int answer = 0;
String binary=””;
int oneCount=0;
boolean check=true;
//2진수를 구하면서 1의 갯수를 구함
while(true){
if(n%2==1){
binary=1+binary;
oneCount++;
}else{
binary=0+binary;
}
if(n<=1){
break;
}
n=n/2;
}

    int tempOneCount=0;  
    int tempN = addN;  
  
    while(check){  
        while(true){  
            if(tempN%2==1){  
                tempOneCount++;  
            }  
            if(tempN<=1){  
                break;  
            }  
            tempN=tempN/2;  
        }  
        if(tempOneCount==oneCount){  
            answer = addN;  
            check=false;  
        }else{  
            tempN = ++addN;  
            tempOneCount=0;  
        }  
  
    }  
    System.out.println(binary);  
    System.out.println(oneCount);  
  
    return answer;  
}   }