int를 이진수의 문자열로 변환 후 문자열 중 1의 개수를 리턴하는 getOneLen(int n) 메소드를 만들어 활용했다.
while문을 통해 origin int n의 이진수일 때 1의 개수(oneLen)과 n이 점점 커짐에 따라 커진 n의 이진수 일 때 1의 개수가 같아질 경우 반복문을 탈출하고, 해당 n을 리턴하도록 구성했다. 문제 제한 조건에 같지 않을 경우에 대한 명시가 없어 while문을 통해 간단하게 풀이했다.
NextBigNum.java
package com.example.Programmers.Lv2;
/**
* 프로그래머스 Lv2 - 다음 큰 숫자
*/
public class NextBigNum {
public int solution(int n) {
int oneLen = getOneLen(n);
n++;
while (oneLen != getOneLen(n)) {
n++;
}
return n;
}
public int getOneLen(int n) {
String nBinaryStr = Integer.toBinaryString(n);
int oneRemovedLen = nBinaryStr.replace("1", "").length();
return nBinaryStr.length() - oneRemovedLen;
}
}
NextBigNumTest.java
package com.example.Programmers.Lv2;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class NextBigNumTest {
@Test
public void testNextBigNum() {
NextBigNum nbn = new NextBigNum();
int result1 = nbn.solution(78);
int result2 = nbn.solution(15);
assertEquals(83, result1);
assertEquals(23, result2);
}
}