티스토리 뷰
728x90
코딩테스트 연습 - 다음 큰 숫자
자연수 n이 주어졌을 때, n의 다음 큰 숫자는 다음과 같이 정의 합니다. 조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다. 조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니
programmers.co.kr
//다른사람코드
public int solution2(int n) {
int answer = Integer.bitCount(n);
while(true) {
n++;
if(answer == Integer.bitCount(n) ) {
answer = n;
break;
}
}
return answer;
}
public int solution(int n) {
int answer = 0;
String binary = Integer.toBinaryString(n);
int cnt = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
cnt++;
}
}
String tempStr = "";
while (true) {
n++;
int tempCnt = 0;
tempStr = Integer.toBinaryString(n);
for (int i = 0; i < tempStr.length(); i++) {
if (tempStr.charAt(i) == '1') {
tempCnt++;
}
}
if (cnt == tempCnt) {
break;
}
}
answer = Integer.parseInt(tempStr, 2);
return answer;
}
이진수 변환 함수
Integer.toBinaryString(n)
이진수에서 1의 개수를 세어주는 함수
Integer.bitCount(n);
내부 코드
@HotSpotIntrinsicCandidate
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
'알고리즘 - Java' 카테고리의 다른 글
[프로그래머스] 로또의 최고 순위 와 최저 순위 - Java (0) | 2022.04.09 |
---|---|
[프로그래머스] k 진수에서 소수 구하기 - Java (0) | 2022.04.09 |
[Programmers] 예상 대진표 - Java (0) | 2022.03.31 |
[Programmers] 피로도 - Java (0) | 2022.03.31 |
[Programmers] 큰 수 만들기 - Java (0) | 2022.03.30 |
댓글