JAVA 코딩테스트 대비-12. 암호(replace(), parseInt(string, 2))

리만·2023년 11월 28일

섹션 1. String 문자열 : 암호

#와 * 로 이루어진 7자리는 한 문자이며 #는 1 *는 0으로 치환한 2진수를 10진수로 바꾸어 해당 아스키 번호로 변환한다.

💻 강의 코드

class Algorithm {
	public String solution(int n, String s) {
        String answer = "";
        for (int i = 0; i < n; i++) {
            String tmp = s.substring(0, 7).replace('#', '1').replace('*', '0');
            int num = Integer.parseInt(tmp, 2)
            s = s.substring(7);
        }
        return answer;
    }
	public static void main(String[] args){
		Algorithm T = new Algorithm();
		Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();
        String str = kb.next();
        System.out.println(T.solution(n, str));
    }
}



💻 IntelliJ - Service

@Service
public class StringAlgorithmService{
	 public String decoding(int n, String str) {
        String answer = "";
        // 1. 입력 받은 정수만큼 7자리씩 자른다.
        for (int i = 0; i < n; i++) {
            // 2. 7자리씩 자른 후 #->1, *->0으로 치환한다.(replace)
            String temp = str.substring(0, 7).replace('#', '1').replace('*', '0');
            // 3. 2진수 -> 10진수로 변환
            int num = Integer.parseInt(temp, 2);
            // 4. 문자로 형 변환
            answer += (char) num;
            // 5. index 7부터 끝까지로 str 갱신
            str = str.substring(7);
        }
        return answer;
    }
}
@Test
@DisplayName("암호")
    void decode() {
        String str = "#****###**#####**#####**##**";
        int n = 4;
        String answer = stringAlgorithmService.decoding(n, str);
        System.out.println("result ====> " + answer);
    }
    

💻 결과

💻 NOTE

  • Integer.parseInt(temp, n) : n진수인 temp를 10진수로 변환

출처 : 인프런 자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비

0개의 댓글