https://www.acmicpc.net/problem/3460
Answer
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
int T = 0;
int n = 0;
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
T = Integer.parseInt(br.readLine());
for (int i = 0; i < T; i++) {
n = Integer.parseInt(br.readLine());
calculateBinary(n);
}
} catch (IOException e) {
System.err.println("ERROR = " + e.getMessage());
}
}
static void calculateBinary(int n) {
StringBuilder binary = new StringBuilder();
int oneCount = 0;
while (n != 0) {
if (n % 2 == 1) {
binary.append(oneCount).append(" ");
}
n /= 2;
oneCount++;
}
System.out.println(binary);
}
}
Code Review
int T = 0;
int n = 0;
테스트 케이스의 개수 T와 양의 정수 n을 선언한다.
T는 첫째 줄에 나오는데 만약에 T가 2라면 주어지는 n의 개수는 2개가 되어 아래처럼 입력이 총 3줄이 될 것이다.
2
13
7
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
...
} catch (IOException e) {
System.err.println("ERROR = " + e.getMessage());
}
`try-with-resources`로 try에 객체의 자원을 받아서 try 문이 끝날 때 그 자원을 반환한다.
`System.in`으로 사용자로부터 입력받은 데이터를 바이트 스트림으로 받는다.
`InputStreamReader` 클래스로 바이트 스트림을 문자 기반 스트림으로 변환한다.
`BufferedReader` 클래스로 문자 스트림을 읽는다.
T = Integer.parseInt(br.readLine());
for (int i = 0; i < T; i++) {
n = Integer.parseInt(br.readLine());
calculateBinary(n);
}
try 문 안의 로직이다.
첫째 줄에 입력받은 테스트 케이스 개수를 T에 대입한다. 이때 입력받은 형식은 String이므로 `Integer.parseInt()`를 사용하여 int로 형변환 시켜준다.
T번 계산을 해야 되기 때문에 for문으로 계산 로직을 반복해 준다.
첫째 줄 밑으로는 양의 정수 n이 주어지기 때문에 T와 마찬가지로 String을 int로 변환해 주는 `Integer.parseInt()`를 사용한다.
이제 생성한 계산 로직 `calculateBinary()` 메서드에 n을 인수로 넣어 실행한다.
static void calculateBinary(int n) {
StringBuilder binary = new StringBuilder();
int oneCount = 0;
while (n != 0) {
if (n % 2 == 1) {
binary.append(oneCount).append(" ");
}
n /= 2;
oneCount++;
}
System.out.println(binary);
}
이진수에서 1의 위치를 출력하기 위한 `StringBuilder` 객체를 생성한다.
이진수에서 1의 위치를 나타내는 `oneCount` 변수를 생성한다.
양의 정수 while문 안에서 `n /= 2` n을 2로 나누어 0이 되기 전까지 반복하면서 `oneCount++` 위치값도 올려준다.
반복하면서 `n % 2 == 1` n을 2로 나누었을 때 나머지가 1이면 그 시점의 `oneCount` 이진수 1의 위치를 `binary` 객체에 추가한다.
십진수 6을 이진수로 변환 시
6 / 2 = 3, 6 % 2 = 0
3 / 2 = 1, 3 % 2 = 1
1 / 2 = 0, 1 % 2 = 1
따라서 이진수는 110이 되고, 1의 위치는 1, 2가 된다.
1 / 2가 0.5가 아니고 0인 이유
(int) / (int)는 버림 연산을 하기 때문에 1 / 2 = 0이 되는 것이다.
만약 0.5가 나오게 하려면 (double) / (int) 또는 (int) / (double)로 계산해야 된다.
while문을 반복이 끝나면 이진수에서 1의 위치를 출력한다.
Result