기본 콘텐츠로 건너뛰기

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

내 풀이는 좀 허접..
{
    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));
    }
}

댓글

이 블로그의 인기 게시물

맥스 어만(Max Ehrmann) - 소망(진정 바라는 것)

진정 바라는 것                                                                       -맥스 어만 소란스럽고 바쁜 일상속에서도  침묵 안에 평화가 있다는 사실을 기억하십시오 포기하지 말고 가능한한 모든 사람들과 잘 지내도록 하십시오 조용하면서도 분명하게 진실을 말하고  어리석고 무지한 사람들의 말에도 귀를 기울이십시오  그들 역시 할 이야기가 있을테니까요  목소리가 크고 공격적인 사람들은 피하십시오  그들은 영혼을 괴롭힙니다 자신을 다른 사람들과 비교하면 자신이 하찮아 보이고  비참한 마음이 들수도 있습니다  더 위대하거나 더 못한 사람들은 언제나...