1.이진변환 문제
- 프로그래머스 Level 2 정답률 70%가 넘는 쉬운 이진변환 문제에서 배운 것
1) 문자열로 이진수가 주어짐
2) 그 이진수를 0을 빼고 뺀 0의 수를 카운트
3) 0을 빼고 남은 1로만 이루어진 이진수의 길이를 이진법으로 변환 ( ex. 1111 -> 길이4 -> 100 )
4) 그렇게 만들어진 이진수를 1만 남을 때 까지 돌림
5) 만드는 과정 중 뺀 0의 총 갯수와, 그렇게 만들기 까지의 횟수를 반환하기
- 예시 :
"110010101001" -> [3,8]
2. 본인 풀이
- 접근 :
1) 굳이 이진수로 또 변환해서 돌려줘야하나? 라는 생각이 들었음
2) 따라서 0을 제외한 1의 갯수를 카운팅 하는 것으로 접근했음
public class Solution6 {
public static int[] solution(String s) {
int zeroCount = 0;
int oneCount = 0;
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '0') {
zeroCount += 1;
}
if (s.charAt(i) == '1') {
oneCount += 1;
}
}
count++;
while(oneCount!=1){
int res = oneCount;
oneCount = 1;
while(res!=1){
if(res%2==0){
res = res/2;
zeroCount+=1;
}else{
res = res/2;
oneCount+=1;
}
}
count++;
}
return new int[]{count,zeroCount};
}
}
3. 다른 사람의 접근
- int자료형 숫자를 String 이진수로 변환해주는 Integer 클레스의 toBinarytoString()이라는 static메서드가 존재했음.
- 예) Integer.toBinarytoString(6) = "110"
public static int[] solution(String s) {
int zeroCount = 0;
int oneCount = 0;
int count = 0;
String sCh = s;
while(!sCh.equals("1")) {
for (int i = 0; i < sCh.length(); i++) {
if (sCh.charAt(i) == '0') {
zeroCount += 1;
}
if (sCh.charAt(i) == '1') {
oneCount += 1;
}
}
sCh = Integer.toBinaryString(oneCount);
oneCount = 0;
count++;
}
System.out.println(count+" "+zeroCount);
return new int[]{count,zeroCount};
}