프로그래머스 다음 큰 숫자
2021. 1. 3. 19:11ㆍ알고리즘
다음 큰 숫자 : programmers.co.kr/learn/courses/30/lessons/12911
코딩테스트 연습 - 다음 큰 숫자
자연수 n이 주어졌을 때, n의 다음 큰 숫자는 다음과 같이 정의 합니다. 조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다. 조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니
programmers.co.kr
자연수 n의 다음 큰 수 에대한 정의가 주어지고 이때 그 정의를 만족하는 수중 가장 작은수를 출력해주는 문제였다.
이 문제를 풀며 오늘 처음 알았던 함수가 있는데 bitCount라는 함수였다 Integer 래퍼클래스에 존재하는 함순데 이는 2진수로 나타낸 숫자에서 1의 갯수를 세어주는 함수이다.(근데 나는 이거 알고도 어렵게품...ㅠ)
먼저 내가 뻘짓하면서 어렵게 푼 코드이다.
import java.util.*;
class Solution {
public int solution(int n) {
String binary = Integer.toBinaryString(n);
String result = "";
int idx = binary.lastIndexOf("1");
int count = 0, lastIdx = 0;
char[] arr = binary.toCharArray();
while (true) {
if (idx == 0) {
char[] temp = new char[binary.length() + 1];
temp[0] = '1';
lastIdx = temp.length - 1;
for (int i = 0; i < count; i++) {
temp[lastIdx--] = '1';
}
for (int i = 1; i <= lastIdx; i++) {
temp[i] = '0';
}
result = new String(temp);
break;
}
if (arr[idx - 1] == '0') {
arr[idx] = '0';
arr[idx - 1] = '1';
result = new String(arr);
lastIdx = binary.length() - 1;
for (int i = count; i > 0; i--) {
arr[lastIdx--] = '1';
}
for (int i = idx; i <= lastIdx; i++) {
arr[i] = '0';
}
result = new String(arr);
break;
} else {
idx--;
count++;
}
}
return Integer.parseInt(result, 2);
}
}
풀고난후 더쉽게 푸는 방법이 떠올랐는데 다음은 쉽게 짠 코드이다.
import java.util.*;
class Solution {
public int solution(int n) {
int n_bit = Integer.bitCount(n);
while(true){
if(n_bit == Integer.bitCount(++n)){
break;
}
}
return n;
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 폰켓몬 (0) | 2021.01.03 |
---|---|
프로그래머스 땅따먹기 (0) | 2021.01.03 |
프로그래머스 올바른 괄호 (0) | 2021.01.03 |
프로그래머스 튜플 (0) | 2021.01.02 |
프로그래머스 단체사진 찍기 (0) | 2021.01.02 |