알고리즘

[프로그래머스, 자바, 12911번] 다음 큰 숫자

hminor 2024. 9. 4. 00:47

풀이

  • 그냥 단순하게 해결했으며, 문법적인 것으로 알게된 것은
  • 2진, 8진, 16진 변경은 아래와 같다.
    • Integer.toBinaryString() -> 2진
    • Integer.toOctalString() -> 8진
    • Integer.toHexaString() -> 16진
  • 그리고 파이썬처럼 문자열 안에 특정 문자가 몇 개있는지 찾는 find()와 같은 함수가
  • 따로 없는 듯 하여 아래 코드와 같이 해결할 수 있음을 상기 시킴.

 

class Solution {
    public int solution(int n) {
        int n_cnt = find(n);
        int result = 0;
        for (int i=n+1; i<=1000000; i++) {
            if (n_cnt == find(i)) {
                result = i;
                break;
            };
        }
        
        return result;
    }
    public static int find(int n) {
        String b_n = Integer.toBinaryString(n);
        int cnt = b_n.length() - b_n.replace("1","").length();
        return cnt;
    }
}