1916: 【基础】-2进制
时间限制: 1 Sec 内存限制: 32 MB
提交: 507 解决: 292
[提交] [状态] [讨论版] [命题人:外部导入]
题目描述
对于十进制整数N,试求其-2进制表示。 例如,因为 1*1 + 1*-2 + 1*4 + 0*-8 +1*16 + 1*-32 = -13 ,所以(-13)_10 = (110111)_-2。
输入
一个整数,代表要转换的十进制数。
输出
一个整数,代表N的-2进制表示。
样例输入
-13
样例输出
110111
提示
|N| < = 2000000000
题解如下
#include<iostream>
#include<stack>
#include<algorithm>
#include<math.h>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
stack<int> res;
if(n==0)
{
printf("0");
}
else
{
while (n)
{
int a=abs(n%-2);
res.push(a);
n=(n-a)/-2;
}
while (!res.empty())
{
printf("%d",res.top());
res.pop();
}
}
printf("\n");
return 0;
}