문제 Link
https://school.programmers.co.kr/learn/courses/30/lessons/70129
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제풀이 Key Point
- 2진수 변환하기
- 0을 제거하면서 카운팅 하기
- 변환할 숫자가 1이 될때까지 위 작업 반복하기
Java 문제풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import java.util.Stack;
class Solution {
public int[] solution(String s) {
int count = 0;
int zeroCount = 0;
while (!s.equals("1")) {
zeroCount += getZeroCount(s);
s = removeZero(s);
Stack<String> stack = getConvertBinary(s);
s = getConvertBinaryResult(stack);
count++;
}
int[] answer = new int[]{count, zeroCount};
return answer;
}
private String getConvertBinaryResult(Stack<String> stack) {
String value = "";
while (!stack.isEmpty()) {
value += stack.pop();
}
return value;
}
private Stack<String> getConvertBinary(String value) {
int stringLength = value.length();
Stack<String> stack = new Stack<>();
while (stringLength > 0) {
stack.push(String.valueOf(stringLength % 2));
stringLength /= 2;
}
return stack;
}
private String removeZero(String value) {
return value.replaceAll("0", "");
}
private long getZeroCount(String value) {
return value.chars()
.filter(ch -> ch == '0')
.count();
}
}
|
cs |
'알고리즘 문제풀이' 카테고리의 다른 글
[프로그래머스 12909] Level2 올바른 괄호 (0) | 2022.09.11 |
---|---|
[프로그래머스 12941] Level2 최솟값 만들기 (0) | 2022.09.09 |
[프로그래머스 1844] Lv.2 게임 맵 최단거리 (0) | 2022.08.27 |
[프로그래머스 43162] Lv.3 네트워크 (0) | 2022.08.26 |
[프로그래머스 43165] Lv.2 타겟 넘버 (0) | 2022.08.26 |