https://school.programmers.co.kr/learn/courses/30/lessons/70129
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
- 런타임에러 (틀린 답)
class Solution {
public int[] solution(String s) {
int[] answer = new int[2];
int zero = 0; // 제거한 0의 개수
int cnt = 0; // 바퀴수
int change = Integer.parseInt(s, 2); // 2진수 -> 10진수
while(change != 1){
String bn = "";
if(cnt == 0){
bn = s;
}else{
bn = Integer.toBinaryString(change); // 10진수 -> 2진수
}
String cbn = "";
for(int i = 0; i < bn.length(); i++){
if(bn.charAt(i) == '1'){
cbn += bn.charAt(i);
}else{
zero++;
}
}
bn = Integer.toBinaryString(cbn.length()); // 0을 제거한 이진수의 길이
change = Integer.parseInt(bn, 2); // 바뀐 2진수를 10진수로 변환하여 1인지 확인
cnt++;
}
answer[0] = cnt;
answer[1] = zero;
return answer;
}
}
/*
1. 이진변환 -> 0 제거한 후 길이 구함
2. 그 길이를 다시 이진수로 변환
3. 위 과정을 반복하며 이진수로 변환한 수의 값이 1이 될 때까지 반복
*/
- 맞은 답
class Solution {
public int[] solution(String s) {
int[] answer = new int[2];
while(s.length() > 1) {
int cntOne = 0; // 1 개수 세기
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) == '0') {
answer[1]++; // 0 개수 세기
}else{
cntOne++;
}
}
s = Integer.toBinaryString(cntOne); // 1 개수에 따른 이진수 변환
answer[0]++;
}
return answer;
}
}'코딩테스트 > 코딩테스트 문제풀이' 카테고리의 다른 글
| [Java] 프로그래머스 <의상> (0) | 2025.02.22 |
|---|---|
| [Java] 프로그래머스 <n^2 배열 자르기> (0) | 2025.02.22 |
| [Java] 프로그래머스 <JadenCase 문자열 만들기> (0) | 2025.02.16 |
| [Java] 프로그래머스 <최댓값과 최솟값> (0) | 2025.02.15 |
| [Java] 프로그래머스 <영어 끝말잇기> (0) | 2025.02.15 |