반응형
[프로그래머스] 다음 큰 숫자
https://programmers.co.kr/learn/courses/30/lessons/12911
문제 접근
처음에 접근할 때는 Integer.toBinaryString() 함수를 이용해서 string형태의 2진수로 변환한 후 1의 개수를 세고, n+1부터 1의 개수가 같을 때까지 while문을 돌렸다.
다 풀고 다른 사람의 풀이를 보니까 Integer.countBit()를 이용하면 1의 개수를 반환해주는 함수가 있어서 더 쉽게 풀었다.
Code
Integer.toBinaryString()이용한 풀이
class Solution {
public int solution(int n) {
String binaryNum = Integer.toBinaryString(n);
int oneCnt = countOne(binaryNum);
int newCnt = -1;
int newNum = n;
while(oneCnt != newCnt){
newNum++;
newCnt = countOne((Integer.toBinaryString(newNum)));
}
return newNum;
}
public int countOne(String str){
int cnt = 0;
for(char ch: str.toCharArray()){
if(ch == '1') cnt++;
}
return cnt;
}
}
Integer.bitCount()이용한 풀이
class Solution {
public int solution(int n) {
int oneCnt = Integer.bitCount(n);
int newCnt = -1;
int newNum = n;
while(oneCnt != newCnt){
newNum++;
newCnt = Integer.bitCount(newNum);
}
return newNum;
}
}
어려웠던 점 / 배운 점 / 느낀 점
정말 유용한 함수들이 너무 많다... 오늘도 이렇게 bitCount를 배워간다...
반응형
'Algorithm' 카테고리의 다른 글
[Algorithm/Java][백준] 1865 웜홀 (0) | 2022.04.07 |
---|---|
[Algorithm/Java][프로그래머스] 타겟 넘버 (0) | 2022.04.06 |
[Algorithm/Java][백준] 1167 트리의 지름 (0) | 2022.04.04 |
[Algorithm/Java][백준] 1967 트리의 지름 (0) | 2022.04.04 |
[Algorithm/Java][백준] 11729 하노이 탑 이동 순서 (0) | 2022.04.01 |