본문 바로가기

Algorithm

[Algorithm/Java][프로그래머스] 다음 큰 숫자

반응형

[프로그래머스] 다음 큰 숫자

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

문제 접근

처음에 접근할 때는 Integer.toBinaryString() 함수를 이용해서 string형태의 2진수로 변환한 후 1의 개수를 세고, n+1부터 1의 개수가 같을 때까지 while문을 돌렸다.
다 풀고 다른 사람의 풀이를 보니까 Integer.countBit()를 이용하면 1의 개수를 반환해주는 함수가 있어서 더 쉽게 풀었다.

Code

Integer.toBinaryString()이용한 풀이

class Solution {
    public int solution(int n) {
        String binaryNum = Integer.toBinaryString(n);
        int oneCnt = countOne(binaryNum);
        int newCnt = -1;
        int newNum = n;
        while(oneCnt != newCnt){
            newNum++;
            newCnt = countOne((Integer.toBinaryString(newNum)));
        }
        return newNum;
    }

    public int countOne(String str){
        int cnt = 0;
        for(char ch: str.toCharArray()){
            if(ch == '1') cnt++;
        }
        return cnt;
    }
}

Integer.bitCount()이용한 풀이

class Solution {
    public int solution(int n) {
        int oneCnt = Integer.bitCount(n);
        int newCnt = -1;
        int newNum = n;
        while(oneCnt != newCnt){
            newNum++;
            newCnt = Integer.bitCount(newNum);
        }
        return newNum;
    }
}

어려웠던 점 / 배운 점 / 느낀 점

정말 유용한 함수들이 너무 많다... 오늘도 이렇게 bitCount를 배워간다...

반응형