혼자 공부,정리하는 알고리즘
[Algorithm] 프로그래머스 - 다음 큰 숫자 (Java)
guriguriguri
2021. 10. 14. 23:16
[문제]
https://programmers.co.kr/learn/courses/30/lessons/12911?language=java
코딩테스트 연습 - 다음 큰 숫자
자연수 n이 주어졌을 때, n의 다음 큰 숫자는 다음과 같이 정의 합니다. 조건 1. n의 다음 큰 숫자는 n보다 큰 자연수 입니다. 조건 2. n의 다음 큰 숫자와 n은 2진수로 변환했을 때 1의 갯수가 같습니
programmers.co.kr
[나의 풀이]
class Solution {
public int solution(int n) {
int answer = 0;
String binaryN = Integer.toBinaryString(n);
int next = n;
while(true){
String binaryNextN = Integer.toBinaryString(++next);
if(countChar(binaryN,'1') == countChar(binaryNextN,'1')){
answer = next;
break;
}
}
return answer;
}
public static int countChar(String str,char ch){
return str.length() - str.replace(String.valueOf(ch),"").length();
}
}
1) 제시된 매개변수 n을 2진수로 변환 (binaryN)
2) n을 1씩 증가시킨 후 2진수로 변환 (binaryNextN)
3) binaryN과 binaryNextN 두 문자열에서 1의 갯수를 반환하는 함수 countChar()를 사용하여 1의 갯수가 같은지 비교
4) 1의 갯수가 같다면 while 반복문 break
하는 방식으로 문제를 풀었지만 효율성 테스트에서 시간 초과로 통과하지 못했다.
[향상된 나의 풀이]
class Solution {
public int solution(int n) {
int bitCount = Integer.bitCount(n);
while(true){
if(bitCount == Integer.bitCount(++n)){
break;
}
}
return n;
}
}
Integer 클래스에 내장된 메소드 중 bitCount(int i) 라는 숫자 데이터의 비트데이터(2진데이터이며 binary데이터) 중 1 비트의 수를 카운트해주는 메소드를 이용하여 더 간결하게 작성하여 효율성 테스트도 통과하였다.