programmers.co.kr/learn/courses/30/lessons/70129
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
#문제 설명
0과 1로 이루어진 어ㄸ너 문자열 x에 대한 이진 변환을 다음과 같이 정의합니다.
1. x의 모든 0을 제거합니다.
2. x의 길이를 c라고 하면, x를 c를 2진법으로 표현한 문자열로 바꿉니다.
위 과정을 x가 1이 될때까지 반복하며 전체 반복 횟수와 0을 없앤 횟수를 반환하시오.
#나의 풀이
class Solution {
public int[] solution(String x) {
int[] answer = {};
int count = 0;
int whileCount = 0;
int zeroCount = 0;1
String binaryNum = ""; //111, 11, 10, 1
while(!binaryNum.equals("1")){ //이진수로 변환한 값이 1이 될때까지 반복
whileCount++; //전체 반복횟수
count = 0; //현재 이진수 0개수 초기화
binaryNum = "";
System.out.println("whileCount" + whileCount);
System.out.println("zeroCount" + zeroCount);
for(int i = 0; i < x.length(); i++){ //count에 0 개수 저장
if(x.charAt(i) == '0'){
count++; //현재 이진수의 0개수
zeroCount++;//전체 이진수의 0개수
}
}
x = x.replaceAll("0", ""); //0 없애기
while(count != 0){ //binaryNum에 2진수로 변환한것 대입
x += Integer.toString(count % 2);
count /= 2;
for(int i = x.length() - 1; i >= 0; i--){
binaryNum += x.charAt(i);
}
System.out.println("binaryNum" + binaryNum);
}
x = binaryNum;
}
return answer;
}
}
#실패에서 얻어가는 지식
1. String에서 특정 문자 개수 구하는법 (1)
String str = "Hello";
System.out.println(countChar(str, 'H')); //1
countChat을 사용하여 개수를 구한다. 매개체(1)은 검색할 문자열, 매개체(2)는 문자열에서 찾을 문자이다.
2. String에서 특정 문자 개수 구하는법 (2)
String str = "Hello";
int count = 0;
for(int i = 0; i < str.length(); i++) {
if(x.charAt(i) == '0'){
count++;
}
}
반복문과 charAt을 통해 각각의 문자를 비교하는 방법이다.
3.문자열에서 특정문자 삭제하기(변환하기)
String str = "10101"
str.replaceAll("0", ""); //0을 공백으로 변환
replaceAll("0", "1");
replaceAll("0", "0");
4. int to String / String to int 변환
//String to int
String from = "123";
int to = Integer.parseInt(from);
//int to String
int from = 123;
String to = Integer.toString(from);
Integer.toString()
Integer.parseInt()
#해답
class Solution {
public int[] solution(String s) {
int[] answer = new int[2];
while(s.length() > 1) {
int cntOne = 0;
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) == '0') answer[1]++;
else cntOne++;
}
s = Integer.toBinaryString(cntOne);
answer[0]++;
}
return answer;
}
}
#해답에서 얻어가는 지식
1. Integer.toBinaryString();
System.out.println(Integer.toBinaryString("6")); //110
int to BinaryString: 10진수를 2진수문자열로 치환. -> Integer.toBinaryString();
'💡알고리즘' 카테고리의 다른 글
[프로그래머스/JAVA] Level 2. 숫자의 표 (0) | 2023.04.19 |
---|---|
LV2. 최솟값 만들기 With Java (0) | 2023.04.11 |