티스토리 뷰
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Stack<Integer> stack = new Stack<>();
int input = Integer.parseInt(in.readLine());
final int dividor = -2;
if(input == 0) {
System.out.println(0);
return;
}
while(input != 0) {
int quotient = input / dividor;
if(quotient * dividor < input) {
stack.push(1);
input = quotient;
} else if(quotient * dividor > input) {
quotient += 1;
stack.push(1);
input = quotient;
} else {
stack.push(0);
input = quotient;
}
}
while(!stack.isEmpty()) {
System.out.print(stack.pop());
}
System.out.println();
}
}
일단 종이를 준비하고, 주어진 수를 -2로 나누어가며 나머지가 0 또는 1만 나오게 적어본다.
그러면 풀 수 있다!
import Foundation
var input = Int(readLine()!)!
var stack = [Int]()
let dividor = -2
if input == 0 {
print(0)
exit(0)
}
while input != 0 {
var quotient = input / dividor
if quotient * dividor < input {
stack.append(1)
} else if quotient * dividor > input {
quotient += 1
stack.append(1)
} else {
stack.append(0)
}
input = quotient
}
while !stack.isEmpty {
print(stack.popLast()!, terminator: "")
}
print()
'Algorithm > Baekjoon Online Judge' 카테고리의 다른 글
1929번 '소수 구하기' (0) | 2018.08.01 |
---|---|
11576번 'Base Conversion' (0) | 2018.08.01 |
1212번 '8진수 2진수' (0) | 2018.07.31 |
1373번 '2진법 8진법' (0) | 2018.07.31 |
2745번 '진법 변환' (0) | 2018.07.31 |
댓글