다음 큰 숫자

이준경·2021년 5월 24일
0

<나의풀이>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public int solution(int n) {
        int answer = 0;
        String s = Integer.toBinaryString(n);
        int cnt=0;
        
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i)=='1')
                cnt++;
        }
 
        while(true){
            String ss = Integer.toBinaryString(++n);
            int cnt1=0;
            for(int i=0; i<ss.length(); i++){
                if(ss.charAt(i)=='1')
                    cnt1++;
            }
            if(cnt==cnt1)
                return n;
        }
    }
  
}
cs
  1. 주어진 수를 toBinaryString으로 2진법으로 변환.
  2. 문자열이 1이면 cnt증가
  3. ++n을 2진법으로 변환후 1의 갯수만큼 cnt1증가
  4. cnt==cnt1 일 경우 n리턴

<다른사람풀이>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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));
    }
}
cs

bitCount()를 이용한 풀이. bitCount(num)은 num을 비트 즉, 2진법으로 변환 했을때 1의 개수를 리턴해주는 함수이다.

0개의 댓글

관련 채용 정보