코딩테스트/프로그래머스
[프로그래머스] 다음 큰 숫자 - JAVA
ankisile
2023. 6. 26. 21:40
문제
https://school.programmers.co.kr/learn/courses/30/lessons/12911
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
처음 문제를 보자마자 toBinaryString 함수가 생각났다
toBinaryString을 이용하여 이진수로 바꾸고 값을 1씩 늘리면서 1의 개수를 셌다.
다른 방법으로는 bitCount를 이용하여 비트수를 세는 방법이 있었다.
코드
class Solution {
public int solution(int n) {
String str = Integer.toBinaryString(n);
int n_cnt = 0;
for(int i=0;i<str.length();i++){
if(str.charAt(i) == '1'){
n_cnt+=1;
}
}
int answer = 0;
while(true){
n++;
int cnt = 0;
str = Integer.toBinaryString(n);
for(int i=0;i<str.length();i++){
if(str.charAt(i) == '1'){
cnt+=1;
}
}
if(cnt == n_cnt){
answer = n;
break;
}
}
return answer;
}
}
class Solution {
public int solution(int n) {
int nCnt = Integer.bitCount(n);
int answer = 0;
while(true){
n++;
int cnt = Integer.bitCount(n);
if(nCnt == cnt){
answer = n;
break;
}
}
return answer;
}
}