본문 바로가기
알고리즘 & 자료구조/프로그래머스

다음 큰 숫자

by 신재권 2023. 1. 1.
package programmers;

public class 다음큰숫자 {

   //1. n의 다음 큰 숫자는 n보다 큰 자연수
   //2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때의 1의 갯수가 같다.
   //3. n의 다음 큰 숫자는 조건 1, 2,를 만족하는 수 중 가장 작은 수
   // 78(1001110) 1 = 4개 0 3개
   // 83(1010011) 1 = 4개 0 3개

   public static int solution(int n) {
      int count = Integer.bitCount(n);

      return findNextBiggerNumber(count, n);
   }

   private static int findNextBiggerNumber(int count, int n) {
      while (true) {
         n++;
         int binaryCount = Integer.bitCount(n);

         if (binaryCount == count) {
            return n;
         }
      }
   }

   public static void main(String[] args) {
      System.out.println(solution(78));
      System.out.println(solution(15));
   }

}

'알고리즘 & 자료구조 > 프로그래머스' 카테고리의 다른 글

짝지어 제거하기  (0) 2023.01.03
카펫  (0) 2023.01.02
피보나치 수  (0) 2022.12.31
숫자의 표현  (0) 2022.12.30
이진 변환 반복하기  (0) 2022.12.29