Algorithm/Baekjoon Online Judge

2089번 '-2진수'

할루루 2018. 8. 1. 15:05
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()