[랜덤 마라톤] 이진 딸기(22935)

lhs's avatar
Nov 13, 2024
[랜덤 마라톤] 이진 딸기(22935)
notion image
notion image

1. 문제 풀이 아이디어

1부터 15까지 증가한 후, 2까지 감소하는 한 사이클이 28번 반복된다는 점을 고려하면 문제를 쉽게 풀 수 있다.

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()) - 1) % 28 + 1; n = n > 15 ? 30 - n : n; stringBuilder.append(String.format("%4s", Integer.toBinaryString(n)) .replaceAll("1", "딸기").replaceAll("[ 0]", "V")).append('\n'); } System.out.print(stringBuilder); bufferedReader.close(); } }

3. 정리

  • n1부터 시작하므로, 1을 뺀 후 28로 나눈 나머지를 구하고 다시 1을 더한다.
  • 15부터는 감소하므로, n15보다 클 경우 30 - n으로 계산하여 숫자를 구한다.
  • Integer.toBinaryString 메서드를 사용하여 이진수로 변환하고, String.format 메서드를 사용해 4자리로 맞춘다.
  • replaceAll 메서드를 사용하여, 1"딸기"로, 0과 공백은 "V"로 변환하여 출력한다.

4. 더 좋은 코드 리뷰

notion image
public class Main { String[] arr; private void init() { arr = new String[16]; for (int i = 1; i <= 15; i++) { StringBuilder tmp = new StringBuilder(); for (int j = 3; j >= 0; j--) { tmp.append((i&1<<j)!=0 ? "딸기":"V"); } arr[i] = tmp.toString(); } } private void solution() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); init(); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-->0) { int n = Integer.parseInt(br.readLine()) - 1; n%=28; n++; if (n<=15) { sb.append(arr[n]).append('\n'); } else { sb.append(arr[30-n]).append('\n'); } } System.out.print(sb); } public static void main(String[] args) throws Exception { new Main().solution(); } }
  • i & (1 << 1) 연산을 활용해 숫자 ij번째 비트가 0인지 1인지를 판단한다.
  • 1일 경우 “딸기”, 0일 경우 V를 StringBuilder에 추가한다.
  • 이 과정을 1부터 15까지 반복하여 미리 출력할 결과를 배열에 저장해 성능을 최적화했다.
Share article

LHS's Study Space