
처음엔 1373번 '2진수 8진수' 문제를 풀었을 때 처럼 진수변환하는 기능을 구현하여 변환하려 시도했다.
8진수 ➡️ 2진수 변환 과정
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] octalStr = br.readLine().split("");
int[] octalInt = new int[octalStr.length];
for (int i = 0; i < octalStr.length; i++) {
octalInt[i] = Integer.parseInt(octalStr[octalStr.length-1-i]);
}
int decimal = octalToDecimal(octalInt);
int mod;
while (decimal != 0) {
mod = decimal%2;
sb.append(mod);
decimal = decimal/2;
}
bw.write(sb.reverse()+"\n");
bw.flush();
bw.close();
}
public static int octalToDecimal (int[] octalInt) {
int decimal = 0;
for (int i = 0; i < octalInt.length; i++) {
int eight = 1;
for (int j = 1; j <= i; j++) {
if (i == 0)
break;
eight *= 8;
}
decimal += octalInt[i]*eight;
}
return decimal;
}
}
위의 코드로 프로그램은 잘 돌아갔지만, 시간초과로 오답이 떴다.
찾아보니 진수 변환을 구현하지 않아도 Integer.toBinaryString()이라는 2진수로 변환해주는 메소드가 있기 때문에 이를 활용하면 풀리는 문제였다.
🤷♀️ charAt(i) -'0' 사용 이유
- chatAt(): string 타입으로 받은 문자열을 char 타입으로 한 글자만 받게 해주는 함수
=> 숫자형 문자를 chatAt() 함수로 추출하면 char형이므로 int형으로 변환할 때 아스키코드로 변환됨
👉 '0' 또는 48을 빼주어야 의도대로 계산 가능
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String octalStr = br.readLine();
for (int i = 0; i < octalStr.length(); i++) {
// 문자를 숫자로 바꿔줌
String a = Integer.toBinaryString(octalStr.charAt(i) - '0');
if (a.length() == 2 && i != 0)
a = "0" + a;
else if (a.length() == 1 && i != 0)
a = "00" + a;
sb.append(a);
}
bw.write(sb+"\n");
bw.flush();
bw.close();
}
}
