백준 알고리즘 기초/수학
[백준][수학]-2진법
코딩고치
2019. 9. 13. 22:05
10진수를 입력받아 -2진법 수로 출력하는 문제이다. -2로 나누기를 하기 때문에 나뉘는 수가 양수인지 음수인지 잘 확인을 하여야 한다. 나머지가 음수가 나오지 않도록 코드를 작성하여 스택을 이용하여 출력하였다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#include <iostream>
#include <stack>
using namespace std;
int main(void)
{
int x;
cin >> x;
stack<int> s;
if (x == 0)
cout << "0" << '\n';
else
{
while (1)
{
if (x == 0)
break;
if (x > 0)
{
if (x % 2 == 0)
s.push(0);
else
s.push(1);
x = -(x / 2);
}
else
{
if (x % 2 == 0)
s.push(0);
else
s.push(1);
x = (-x + 1) / 2;
}
}
}
while (!s.empty())
{
cout << s.top();
s.pop();
}
return 0;
}
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |