POJ3191-The Moronic Cowmpouter

The Moronic Cowmpouter
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4006   Accepted: 2079

Description

Inexperienced in the digital arts, the cows tried to build a calculating engine (yes, it's a cowmpouter) using binary numbers (base 2) but instead built one based on base negative 2! They were quite pleased since numbers expressed in base −2 do not have a sign bit.

You know number bases have place values that start at 1 (base to the 0 power) and proceed right-to-left to base^1, base^2, and so on. In base −2, the place values are 1, −2, 4, −8, 16, −32, ... (reading from right to left). Thus, counting from 1 goes like this: 1, 110, 111, 100, 101, 11010, 11011, 11000, 11001, and so on.

Eerily, negative numbers are also represented with 1's and 0's but no sign. Consider counting from −1 downward: 11, 10, 1101, 1100, 1111, and so on.

Please help the cows convert ordinary decimal integers (range -2,000,000,000..2,000,000,000) to their counterpart representation in base −2.

Input

Line 1: A single integer to be converted to base −2

Output

Line 1: A single integer with no leading zeroes that is the input integer converted to base −2. The value 0 is expressed as 0, with exactly one 0.

Sample Input

-13

Sample Output

110111

Hint

Explanation of the sample:

Reading from right-to-left:
1*1 + 1*-2 + 1*4 + 0*-8 +1*16 + 1*-32 = -13

Source

USACO 2006 February Bronze

思路:
转化成为-2进制,原理同2进制相同。
举例模拟一个,整数10的情况
10/-2=-5......0
-5/-2=3......1
3/-2=-1......1
-1/-2=1......1
1/-2=0......1
0结束
最后的结果就是11110。
整除的情况就是0,如果不能整除,需要进行处理,-1之后再去-2得到商,余数为1。
因为-2进制最后保存只会存在0或者1,不能有其他情况。举例来说:
3/-2商为-1时,余数为1。商为-2时,结果为-1。

0的时候做特殊处理。

代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int main()
{
    int num;
    scanf("%d",&num);
    string s="";
    if(num==0)
    {
        cout<<"0"<<endl;
        return 0;
    }
    while(num!=0)
    {
        int temp=fabs(num);
        if(temp%2)
        {
            s+="1";
            num=(num-1)/(-2);
        }
        else
        {
            s+="0";
            num=num/(-2);
        }
    }
    reverse(s.begin(),s.end());
    cout<<s<<endl;
    return 0;
}


原文地址:https://www.cnblogs.com/lemonbiscuit/p/7776042.html