
나의 풀이
class Solution {
public int solution(int n) {
int answer = 0;
String s = Integer.toBinaryString(n); // 1
int value = 0;
for (char c : s.toCharArray()) { // 2
if (c == '1') value++;
}
while (true) { // 3
n++;
String temp = Integer.toBinaryString(n);
int count = 0;
for (char c : temp.toCharArray()) {
if (c == '1') count++;
}
if (value == count) { // 4
answer = n;
break;
}
}
return answer;
}
}
과정
- n을 이진수로 변환한 문자열 s를 선언
- s의 1의 개수를 센다
- n을 하나씩 증가시키면서 n을 이진수로 변환한 문자열 temp의 1의 개수를 세고, s의 1의 개수와 temp의 1의 개수가 같으면 answer에 삽입하고 break;
다른 사람 풀이
import java.lang.Integer;
class TryHelloWorld
{
public int nextBigNumber(int n)
{
int a = Integer.bitCount(n);
int compare = n+1;
while(true) {
if(Integer.bitCount(compare)==a)
break;
compare++;
}
return compare;
}
public static void main(String[] args)
{
TryHelloWorld test = new TryHelloWorld();
int n = 78;
System.out.println(test.nextBigNumber(n));
}
}
- Integer.bitCount(compare) : 주어진 정수에서 true bit의 개수를 찾는 함수