2진수 8진수
풀이
- 2진수를 8진수로 변환하는 문제
- 쉬운문제라고 생각하겠지만 문제의 조건을 살펴보면 그렇지 않다.
- 우선 인풋으로 들어오는 이진수 값의 길이는 최대 백만길이이다.
- 백만길이의 2진수를 10진수로 변환한고 8진수로 변환하는 방식은 절대 안된다.
- 자바 BigInteger 클래스를 이용해서 해보았지만 WA 가 떴다.
- 역시 구글링
- 2진수를 8진수로 변환하는 방법은 위의 방법 말고 다른 방법이 존재한다.
- 2진수로 들어온 값을 세개씩 묶음으로 잡아버리면 계산이 한결 수월하다.
- 관련링크
- 2진수
- 1010100 이 들어오면 세자리로 묶어주기 위해 길이가 무조건 len mod 3 = 0 이 되어야 한다.
- 1010100 → 001, 010, 100
- 속도
- StringBuilder 사용하였음
- StringBuilder vs StringBuffer vs String
- Immutable vs mutable 하고 결과적으로 이것은 속도와 더불어 메모리적인 측면, 멀티스레딩 측면과 연관되어 있음
- StringBuilder 사용하였음
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
static InputStreamReader isr;
static BufferedReader br;
static OutputStreamWriter osw;
static BufferedWriter bw;
static StringTokenizer st;
public static void main(String[] args) throws IOException {
isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
osw = new OutputStreamWriter(System.out);
bw = new BufferedWriter(osw);
/** 이진수 입력 **/
String line = br.readLine();
/** 세자리씩 맞춤 **/
if(line.length() % 3 != 0) {
while(line.length() % 3 != 0) {
line = "0" + line;
}
}
/** 2진수를 8진수로 바꾸는 방법 : 세자리씩 묶기 **/
StringBuilder sb = new StringBuilder();
int count = 0;
int sum = 0;
for(int i = 0; i < line.length(); i++) {
if(count == 0 && line.charAt(i) == '1') {
sum += 4;
}
else if(count == 1 && line.charAt(i) == '1') {
sum += 2;
}
else if(count == 2 && line.charAt(i) == '1') {
sum += 1;
}
count++;
if(count == 3) {
count = 0;
sb.append(sum);
sum = 0;
}
}
if(count != 0) {
sb.append(sum);
}
bw.write(sb.toString() + "");
bw.flush();
bw.close();
br.close();
}
}
'Problem Solving & Algorithm > BOJ ' 카테고리의 다른 글
20190407 1212번 : 8진수 2진수 (0) | 2019.04.07 |
---|---|
20190406 1652번 : 누울 자리를 찾아라 (0) | 2019.04.06 |
20190405 14891번 : 톱니바퀴 (0) | 2019.04.05 |
20190401 1197번 : 최소 스패닝 트리 (0) | 2019.04.02 |
20190331 14500번 : 테트로미노 (0) | 2019.03.31 |