https://school.programmers.co.kr/learn/courses/30/lessons/70129
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 그대로 풀면 되는 문제입니다.
1. x의 모든 0을 제거
2. x의 길이를 c라고 하면, x를 'c를 2진법으로 표현한 문자열'
예르들어 x="0111010" 이라면,
1.x의 모든 0을 제거 "1111"
2.x의 길이 4를 2진변환
그냥 문자열로 진행하여 replaceAll("0",""); 의 방식으로 하면 코드 길이가 훨씬 짧아질것같습니다.
StringBuilder는 replaceAll 함수는 제공하지 않습니다.
코드입니다.
class Solution { public int[] solution(String s) { int[] answer = new int[2]; StringBuilder sb = new StringBuilder(s); int changecnt=0; int removezerocnt = 0; while(true){ // System.out.println(sb.toString()); if(sb.length() == 1 && sb.charAt(0) =='1') break; for(int i=0;i<sb.length();i++){ if(sb.charAt(i) == '0'){ sb.deleteCharAt(i); i-=1; removezerocnt+=1; } } // System.out.println(sb.toString()); int sblength = sb.length(); System.out.println(sblength); sb = new StringBuilder(Integer.toString(sblength, 2)); changecnt += 1; } answer[0] = changecnt; answer[1] = removezerocnt; return answer; } }
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스][다시풀기]위장 - 해쉬 + 아이디어 (0) | 2023.02.01 |
---|---|
[프로그래머스]전화번호 목록 - 해쉬 + 아이디어 (0) | 2023.01.28 |
[프로그래머스]괄호 회전하기 - 구현 + 스택 (0) | 2023.01.23 |
[프로그래머스] 가장 먼 노드 - 다익스트라 + 그래프 (0) | 2023.01.10 |
[카카오 기출 문제]이모티콘 할인행사 - 레벨 2, 중복순열 + 구현 (0) | 2023.01.07 |