반응형
🔺 문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
🔺 코드
- 틀림
import java.util.*;
class Solution {
public int solution(int n) {
int answer = 0;
String bin = Integer.toBinaryString(n);
System.out.println(bin);
int nCnt = 0;
for(int i = 0 ; i < bin.length() ; i++) {
if(bin.charAt(i) == '1') {
nCnt++;
}
}
int cnt = 0;
int tmp = n;
while(cnt != nCnt) {
tmp++;
String s = Integer.toBinaryString(tmp);
for(int i = 0 ; i < s.length() ; i++) {
if(s.charAt(i) == '1') {
cnt++;
}
}
if(cnt == nCnt) {
answer = tmp;
break;
}
}
return answer;
}
}
tmp를 증가시키면서 2진수 변환 후 1의 갯수를 구하는 방식으로 하려고 했는데
제출하니까 자꾸 시간 에러가 떴음...
- 정답
import java.util.*;
class Solution {
public int solution(int n) {
int answer = 0;
String bin = Integer.toBinaryString(n);
// n에서 1의 갯수 구하기
int nCnt = 0;
for(int i = 0 ; i < bin.length() ; i++) {
if(bin.charAt(i) == '1') {
nCnt++;
}
}
// n을 1씩 증가시키며 2진수 표현에서 1의 개수 계산
for(int i = n + 1 ; ; i++) {
String tmpBin = Integer.toBinaryString(i);
int tmpCnt = 0;
for(int j = 0 ; j < tmpBin.length() ; j++) {
if(tmpBin.charAt(j) == '1') {
tmpCnt++;
}
}
if(tmpCnt == nCnt) {
answer = i;
break;
}
}
return answer;
}
}
✅ 해결 아이디어
-Integer.toBinaryString()
: 십진수를 이진수로 변환 (String형으로 반환)
- n을 1씩 증가시키며 2진수 표현에서 1의 개수 계산 (2번째 for문)
while문에서 n을 1씩 증가시키는 대신 for문을 사용했음! (for문 범위에 주목...)
🔺 다른 풀이들
- 풀이1)
[프로그래머스,Level 2] 다음 큰 숫자 (JAVA 구현)
- 첫 풀이 및 정답풀이 이 문제를 읽은 후, 바로 Integer.toBinaryString() 메서드를 활용해야겠다는 생각이 들었고 바로 정답 처리를 받을 수 있었다. 로직은 간단하다. 1. 입력된 n을 2진수로 변환한다.
fbtmdwhd33.tistory.com
class Solution {
public int solution(int n) {
int answer = 0;
// 1. 입력받은 n의 1 개수를 저장.
int n_cnt = Integer.bitCount(n);
// 2. 증가하는 n의 1 개수를 저장 할 변수.
int b_cnt = 0;
// 3. 무한반복.
while(true){
// 4. n을 증가.
n++;
// 5. 증가된 n의 1 개수를 저장.
b_cnt = Integer.bitCount(n);
// 6. 일치하면, answer에 n을 담고 반복문을 빠져나온다.
if(n_cnt == b_cnt){
answer = n;
break;
}
}
return answer;
}
}
✔ Integer.bitCount()
: 입력된 정수를 2진수로 변환하고, 2진수에 포함된 1을 카운트하는 메소드
- 풀이2)
import java.lang.Integer;
class Main {
public int nextBigNumber(int n) {
int a = Integer.bitCount(n);
int compare = n+1;
while(true) {
if(Integer.bitCount(compare) == a)
break;
compare++;
}
return compare;
}
}
위 코드보다 더 짧게!
(참고)
[프로그래머스] 다음 큰 숫자(JAVA)
Level 2
techhan.github.io
반응형
'코테 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Lv. 2] 짝지어 제거하기 (0) | 2023.04.02 |
---|---|
[프로그래머스/Lv. 2] 이진 변환 반복하기 (0) | 2023.04.02 |
[프로그래머스/Lv. 2] JadenCase 문자열 만들기 (0) | 2023.04.01 |
[프로그래머스/Lv. 2] N개의 최소공배수 (0) | 2023.04.01 |
[프로그래머스/Lv. 2] 숫자의 표현 (0) | 2023.03.31 |