다음 큰 숫자

HeeSeong·2021년 6월 16일
0

프로그래머스

목록 보기
65/97
post-thumbnail

🔗 문제 링크

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


❔ 문제 설명


자연수 n이 주어졌을 때, n의 다음 큰 숫자는 다음과 같이 정의 합니다.

조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다.
조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니다.
조건 3. n의 다음 큰 숫자는 조건 1, 2를 만족하는 수 중 가장 작은 수 입니다.
예를 들어서 78(1001110)의 다음 큰 숫자는 83(1010011)입니다.

자연수 n이 매개변수로 주어질 때, n의 다음 큰 숫자를 return 하는 solution 함수를 완성해주세요.


⚠️ 제한사항


  • n은 1,000,000 이하의 자연수 입니다.



💡 풀이 (언어 : Java & Python)


직관적으로 풀었다. n에서 1씩 커지는 수를 계속 조건에 맞는지 체크하고 맞으면 바로 그 수를 반환한다.

Java

class Solution {
    public int solution(int n) {
        int countOne1 = 0;
        for (char b : Integer.toBinaryString(n).toCharArray()) {
            if (b == '1')
                countOne1++;
        }
        while (true) {
            n++;
            int countOne2 = 0;
            for (char b : Integer.toBinaryString(n).toCharArray()) {
                if (b == '1')
                    countOne2++;
            }
            if (countOne1 == countOne2)
                return n;
        }
    }
}

Python

def solution(n):
    nstr = bin(n)[2:]
    nOneCount = nstr.count("1")
    candidate = n + 1
    
    while(True):
        # 조건2 체크
        cstr = bin(candidate)[2:]
        cOneCount = cstr.count("1")
        if cOneCount != nOneCount:
            candidate += 1
            continue
            
        return candidate     
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글