기본 콘텐츠로 건너뛰기

프로그래머스 - 다음 큰 숫자

내 풀이는 좀 허접..
{
    public int nextBigNumber(int n)
    {
        int answer = 0;
        char temp;
        String a = Integer.toBinaryString(n);
        char[] str = a.toCharArray();
        int idx = a.lastIndexOf("01");
        str[idx] = '1';
        str[idx+1] = '0';
        for(int i=idx+2;i<str.length;i++) {
            if(str[i]=='1') {

                for(int j=str.length-1;j>i;j--) {
                    if(str[j]=='0') {
                        str[j]='1';
                        str[i]='0';
                        break;
                    }                   
                }               
            }
        }
        String b = new String(str);
        answer = Integer.parseInt(b, 2);
        return answer;
    }
    public static void main(String[] args)
    {
        TryHelloWorld test = new TryHelloWorld();
        int n = 78;
        System.out.println(test.nextBigNumber(n));
    }
}
이 코드는 직관적으로 이해가 잘가는 코드
import java.lang.Integer;

class TryHelloWorld
{
    public int nextBigNumber(int n)
    {
      int a = Integer.bitCount(n);
      int compare = n+1;

      while(true) {
        if(Integer.bitCount(compare)==a)
          break;
        compare++;
      }

      return compare;
    }

    public static void main(String[] args)
    {
        TryHelloWorld test = new TryHelloWorld();
        int n = 78;
        System.out.println(test.nextBigNumber(n));
    }
}
이 코드는 약간 넘사벽
class TryHelloWorld {
    public int nextBigNumber(int n) {
        int postPattern = n & -n, smallPattern = ((n ^ (n + postPattern)) / postPattern) >> 2;
        return n + postPattern | smallPattern;
    }
    public static void main(String[] args) {
        int n = 78;
        System.out.println(new TryHelloWorld().nextBigNumber(n));
    }
}

댓글

이 블로그의 인기 게시물

좌표압축

알 고리즘을 풀다 보면 좌표압축이라는 테크닉이 필요합니다. 저는 좌표압축을  "순위가 중요한 알고리즘에서, 입력값의 갯수보다 입력값의 범위가 클 때 사용하는 방법",  이라고 생각하고 있습니다. 1차원의 좌표로 예를 들어보겠습니다. n개의 x값 을 입력 받아, 입력 중 두개의  x1,x2를 선택하여 사이에 존재하는 점의 개수를 구하는 작업이 있다고 가정합시다. x의 범위는 int형의 범위인 -2^31 ~ 2^31-1 이고 중복은 없습니다. n은 5000 이하입니다. 입력은 n : 7, -2^31, -10000, 0 , -2000, 3, 6, 30000 , x1 = -10000, x2 = 30000 대략적으로 보면 그림과 같이 나타나게 됩니다. x1,x2 사이의 값을 구하게 되면 4개의 값이 나오게 됩니다. 이 경우 위의 값들을 아래와 같이 순위를 유지하면서 바꿔주어도 문제를 풀 수가있습니다. 이렇게   바꿔서 풀 수 있는 이유는 값보다 값의 순위가 중요하기 때문 입 니다. 압축좌표가  필요한 예 로, 카카오 코드 페스티벌 5번 캠핑 문제가 될 수 있습니다. 이 경우 좌표  x,y의 범위는 0 ~ 2^31-1  이지만, 입력받는  좌표의 개수는 최대 5000개  입니다. 만약 입력의 좌표를 그대로 반영하여 문제를 푼다고 하면 배열의 크기가 2^31-1 개가 되어야 합니다. 게다가 2차원으로.. 못풉니다. 탐색하다가 시간다 끝날꺼에요. 하지만 입력이 최대의 개수가 최대 5000이라고 했으니 좌표압축을 이용해 입력받은 좌표를 0~5000 으로 매치시키고 풀게되는 것 입니다.