[프로그래머스 알고리즘] 다음 큰 숫자 (level2)

Seongho·2023년 9월 3일
0


https://school.programmers.co.kr/learn/courses/30/lessons/12911

문제 해결

문제를 읽고 가장 먼저 떠오른 방법은 n의 1의 갯수를 구해놓고, n에 1씩 더하며 n과 1의 갯수가 같은 수를 찾는 방법 이었다. 혹시 시간 초과가 나지 않을까 걱정했지만, 구현이 쉬워 일단 풀어 보았는데 해결되었다.

코드

import java.util.*;
//
class Solution {
//    
     public int oneNum(int n){
//        
         int one = 0;
//        
         while(n > 0){
             if(n % 2 == 1){
                 one++;
             }
             n /= 2;
         }
//        
         return one;
     }
//      
    public int solution(int n) {
        int answer = 0;
        int originOneNum = 0, currOneNum = -1;
//        
        originOneNum = oneNum(n);
        while(originOneNum != currOneNum){
            currOneNum = oneNum(++n);
        }
//        
        answer = n;
//        
        return answer;
    }
}

개선

다른 풀이를 보았는데, Java.lang.Integer.bitCount()라는 함수가 있었다.

public static int bitCount(int i)

정수를 입력하면 2진수에서 1(true)의 갯수가 몇개인지 반환하는 함수이다.

개선된 코드

import java.util.*;
//
class Solution {
//      
    public int solution(int n) {
        int answer = 0;
        int originOneNum = 0, currOneNum = -1;
//        
        originOneNum = Integer.bitCount(n);
        while(originOneNum != currOneNum){
            currOneNum = Integer.bitCount(++n);
        }
//        
        answer = n;
//        
        return answer;
    }
}

언젠가 요긴하게 쓸 날이 오겠지...

profile
Record What I Learned

0개의 댓글