Byeon's NOTE
[프로그래머스 알고리즘] level_2 다음 큰 숫자 - java 본문
문제
https://programmers.co.kr/learn/courses/30/lessons/12911
풀이
import java.util.regex.*;
class Solution {
public int solution(int n) {
int answer = 0;
Pattern pattern = Pattern.compile("1");
Matcher matcher = pattern.matcher(Integer.toBinaryString(n));
int ncnt = 0, acnt=0;
while(matcher.find())
ncnt++;
while(true){
n++;
matcher = pattern.matcher(Integer.toBinaryString(n));
while(matcher.find())
acnt++;
if(ncnt==acnt) break;
acnt=0;
}
return n;
}
}
-
Pattern 과 Matcher를 이용하여 풀어 보았습니다.
-
Integer.toBinaryString() 함수로 n을 2진수문자열로 변환한 후 1이 몇개 있는지 Pattern과 Matcher를 이용하여 찾아 카운트 해줍니다.
-
이후 n값을 1씩 증가 시켜주면서 똑같은 방법으로 1의 개수를 카운트하고 ncnt와 acnt가 같다면 반복문을 빠져나오게 하여 풀었습니다.
-
다른 풀이 방법을 보니 Interger.bitCount()라는 함수가 있더군요...................
class Solution {
public int solution(int n) {
int ncnt = Integer.bitCount(n);
while(Integer.bitCount(++n)!=ncnt){}
return n;
}
}
'알고리즘 문제 > 프로그래머스' 카테고리의 다른 글
[프로그래머스 알고리즘] level_2 2018서머코딩 영어 끝말잇기 - java (0) | 2019.03.27 |
---|---|
[프로그래머스 알고리즘] level_2 주식가격 - java (0) | 2019.03.27 |
[프로그래머스 알고리즘] level_2 전화번호 목록 - java (0) | 2019.03.27 |
[프로그래머스 알고리즘] level_2 2018윈터코딩 스킬트리 - java (0) | 2019.03.18 |
[프로그래머스 알고리즘] level_1 시저암호 - java (0) | 2019.03.17 |
Comments