본문 바로가기

코딩테스트/C++

[백준 C++] 2089번: -2진수

https://www.acmicpc.net/problem/2089

 

2089번: -2진수

-2진법은 부호 없는 2진수로 표현이 된다. 2진법에서는 20, 21, 22, 23이 표현 되지만 -2진법에서는 (-2)0 = 1, (-2)1 = -2, (-2)2 = 4, (-2)3 = -8을 표현한다. 10진수로 1부터 표현하자면 1, 110, 111, 100, 101, 11010, 110

www.acmicpc.net

 

#include <iostream>
#include <algorithm>
using namespace std;
 
int main() {
 
    int n;
    string ans;
    cin >> n;
 
    if (n == 0)
    {
        cout << 0;
        return 0;
    }
 
   
    while (n != 0) 
    {
        if (n % -2 == 0)
        {
            ans += "0";
            n /= -2;
        }
        else
        {
            ans += "1";
            n = (n - 1) / -2;
        }
    }
    for (int i = ans.length()-1;i >= 0;i--) {
        cout << ans[i];
    }
 
	return 0;
}