[랜덤 마라톤] The ♡ System(3071)

lhs's avatar
Nov 14, 2024
[랜덤 마라톤] The ♡ System(3071)
notion image
notion image

1. 문제 풀이 아이디어

  • 숫자를 3진수로 변환한 후, 아래에서 위로 올라가며 2는 1-로, 3은 10으로 변환하면 문제를 풀 수 있다.
  • 숫자가 마이너스 일 경우 1과 -를 교체하면 된다.

2. 나의 정답 코드

public class Main { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder stringBuilder = new StringBuilder(); int t = Integer.parseInt(bufferedReader.readLine()); for (int i = 0; i < t; i++) { int n = Integer.parseInt(bufferedReader.readLine()); String s = Integer.toString(n, 3); if (n < 0) s = s.substring(1); int[] three = new int[s.length() + 1]; for (int j = s.length() - 1; j >= 0; j--) { three[j + 1] = three[j + 1] + Character.getNumericValue(s.charAt(j)); if (three[j + 1] > 1) { if (three[j + 1] > 2) three[j + 1] = 0; else three[j + 1] = -1; three[j] = 1; } } for (int j = three[0] != 0 ? 0 : 1; j < three.length; j++) { int val = three[j]; if (val == 1) { stringBuilder.append(n < 0 ? "-" : "1"); } else if (val == -1) { stringBuilder.append(n < 0 ? "1" : "-"); } else { stringBuilder.append(val); } } stringBuilder.append('\n'); } System.out.print(stringBuilder); bufferedReader.close(); } }

3. 정리

  • nInteger.toString(n, 3) 메서드를 사용해 3진수로 변환하여 s에 저장하고, 음수일 경우 substring(1)을 이용해 - 기호를 제거했다.
  • 3진수 문자열을 뒤에서부터 읽어 three 배열에 값을 저장하면서, 각 자릿수가 2일 경우 1-로, 3일 경우 10으로 변환하여 올림 처리를 했다.
  • three 배열에 저장된 값을 조건에 맞게 처리하여 stringBuilder에 추가하고, 최종 결과를 출력했다.
Share article

LHS's Study Space