티스토리 뷰

💻JAVA 코드 바로보기



문제 설명
자연수 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 이하의 자연수 입니다.

입출력 예

n return
78 83
15 23

 


🌼 JAVA 알고리즘


초기화면






풀이과정

주어진 n값에 대해 2진수로 변환했을 때의 1의 개수(nCount)를 구하고,
무한반복으로 n의 값을 1씩 증가시키면서 2진수를 변환했을 때 1의 개수(count)와 nCount의 개수가 일치했을 때 return했다.
class Solution { public int solution(int n) { int answer = 0; int nCount = 0; String binary = Integer.toBinaryString(n); for(int i=0;i<binary.length();i++){ if(binary.charAt(i)=='1') nCount++; } for(n++ ; ; ++n){ int count = 0; String binary2 = Integer.toBinaryString(n); for(int i=0;i<binary2.length();i++){ if(binary2.charAt(i)=='1') count++; } if(count == nCount) return n; System.out.println(count); } } }



처음 n의값과 1씩 증가시킨 이후의 n의 값 모두 중복되는 코드를 사용하여 2진수의 1개수를 세기 때문에
함수를 통해 일반화시켜주었다.




완성코드

class Solution { public int solution(int n) { int answer = 0; int nCount = binaryCount(n); for(n++ ; ; ++n){ int count = binaryCount(n); if(count == nCount) return n; } } public int binaryCount(int n){ int oneCount = 0; String binary = Integer.toBinaryString(n); for(int i=0;i<binary.length();i++){ if(binary.charAt(i)=='1') oneCount++; } return oneCount; } }




링크

 

About Me

💻GitHub/KimSky904 KimSky904 - Overview Department of New Media Software. KimSky904 has 8 repositories available. Follow their code on GitHub. github.com

code-review.tistory.com

 

 

코딩테스트 연습 - 다음 큰 숫자

자연수 n이 주어졌을 때, n의 다음 큰 숫자는 다음과 같이 정의 합니다. 조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다. 조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니

programmers.co.kr

 

댓글