일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 프로그래머스
- springboot
- html
- Spring boot
- 2차원배열
- 목록
- springSecurity
- StyleSheet
- 반복문
- css
- security
- 스프링 부트
- gradle
- 코딩테스트
- 시큐리티로그인
- 리눅스
- programmers
- 로그인
- codingtest
- input태그
- 시큐리티
- JAVA11
- java
- 시큐리티 로그아웃
- sql
- 소스트리
- 싱글톤
- 시큐리티 로그인
- javascript
- Linux
Archives
- Today
- Total
JAVAIARY
프로그래머스 ) 이진 변환 반복하기 본문
문제: https://school.programmers.co.kr/learn/courses/30/lessons/70129
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
import java.util.ArrayList;
class Solution {
public static int[] solution(String s) {
int zeroCnt = 0;
int cnt =0;
while(!s.equals("1")) {
int num = 0; // 1 개수 == 숫자
// 0 제거
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1') {
num += 1;
}else {
zeroCnt++;
}
}
StringBuffer sb = new StringBuffer();
// 2진수로 변환
while (num / 2 != 0) {
if (num%2 == 0) {
sb.append('0');
}else {
sb.append('1');
}
num /= 2;
}
sb.append('1');
//뒤집어서 s에 재할당
s= sb.reverse().toString();
cnt++;
}
int[] answer = {cnt,zeroCnt};
return answer;
}
}
- toBinaryString() 함수를 모르기도 했고, 함수 알고난 뒤에도 오기가 생겨서 따로 이진수 만들어 주도록 했다.
- 원래 이진수를 만드는 이론처 계속 2로 나누어 그 나머지를 채택하는 방식으로 구현
- 처음에는 ArrayList를 사용하여 뒤집을 때도 반복문이 필요했는데,
StringBuffer에 reverse() 기능이 있다는 것을 알게되어 스트링 버퍼를 채택하였다.
class Solution {
public int[] solution(String s) {
int[] answer = new int[2];
int zeroCount=0, count=0;
while(!s.equals("1")){
String num = "";
for(int i=0; i<s.length(); i++){
if(s.charAt(i)=='1'){
num += s.charAt(i);
}else{
zeroCount++;
}
}
s = Integer.toBinaryString(num.length()).toString();
count++;
}
answer[0] = count;
answer[1] = zeroCount;
return answer;
}
}
- Integer.toBinaryString()을 사용한 방식 (승훈's)
※ 2진법은 제공해주는 함수가 있지만 그럼 3진법은...?
'examplePractice' 카테고리의 다른 글
프로그래머스 ) 구슬을 나누는 경우의 수 (0) | 2023.04.08 |
---|---|
프로그래머스 ) 최소 직사각형 (0) | 2023.04.04 |
프로그래머스 ) n^2 배열 자르기 (0) | 2023.04.03 |
프로그래머스) 크레인 인형뽑기 게임 (0) | 2023.03.22 |
프로그래머스) 성격유형 검사하기 (0) | 2023.03.21 |