[프로그래머스, 12911] 다음 큰 숫자 (java)
Problem Solving/Programmers

[프로그래머스, 12911] 다음 큰 숫자 (java)

728x90

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

728x90

메모리: 52.4 MB, 시간: 0.02 ms

사용 알고리즘: 브루트포스 알고리즘, 수학

class Solution {
    public int solution(int n) {
        int answer = 0;
        
        // n을 2진수로 변환했을 때 1의 개수
        int num = 0, tmp = n;
        while(tmp > 0) {
            if(tmp % 2 == 1) num++;
            tmp /= 2;
        }
        
        int next = n, count;
        while(true) {
            count = 0;
            tmp = ++next;
            while(tmp > 0) {
                if(tmp % 2 == 1) count++;
                tmp /= 2;
            }
            
            if(count == num) {
                answer = next;
                break;
            }
        }
        
        return answer;
    }
}
728x90