프로그래머스 다음 큰 숫자 java

2023. 1. 12. 16:39코딩테스트/프로그래머스

문제

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

 

프로그래머스

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

programmers.co.kr

 

숫자 n이 주어졌을 때

1. n보다 크다.

2. n이 이진수일 때 1의 개수와 같다.

3. 1, 2번을 만족하는 가장 작은 수 출력

 

2번 조건에 대한 메소드를 따로 만들고 n+1부터 순차적으로 비교를 하면 되겠다는 생각을 했다.

 

나의 풀이

class Solution {
    public int solution(int n) {
        int answer = n;
        int oneCount = count(n);

        //n보다 숫자가 큰 경우에서 순차적으로 찾아간다.
        while(true) {
            answer++;

            // 1의 숫자를 비교한다.
            if(oneCount == count(answer)) {
                break;
            }
        }

        return answer;
    }

    // 1의 개수를 세어주는 메소드
    public int count(int number) {
        int oneCount = 0;

        while(number > 0) {
            if (number % 2 == 1) oneCount++;
            number /= 2;
        }

        return oneCount;
    }
}

 

나의 풀이2

 

class Solution {
    public int solution(int n) {
        int answer = n;
        String s = Integer.toBinaryString(n);

        int count = countOne(s);

        while(true) {
            answer++;
            String s1 = Integer.toBinaryString(answer);

            int cnt = countOne(s1);

            if(count == cnt) {
                break;
            }
        }

        return answer;
    }

    // 1을 개수 세주는 메소드
    public int countOne(String s) {
        int count = 0;

        for (int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '1') {
                count++;
            }
        }

        return count;
    }
}