描述
将十进制整数转换成二进制数输入
输入数据中含有不多于50个整数n(-2^16<n<2^16)。输出
对于每个n,以11位的宽度右对齐输出n值,然后输出 –> ,再然后输出二进制数。每个整数n的输出,独立占一行。样例输入1
2
0
-12
1样例输出1
2―->10
0–>0
-12–>-1100
1–>1
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int num = 0;
while (cin >> num)
{
string sBinary;
int temp = abs(num);
if (temp == 0)
{
cout << " 0-->0\n";
continue;
}
while (temp)
{
if (temp & 0x01)
sBinary += '1';
else
sBinary += '0';
temp >>= 1;
}
reverse(sBinary.begin(), sBinary.end());
cout.width(11);
cout << num << (num > 0 ? "-->" : "-->-") << sBinary << endl;
}
return 0;
}
巧妙使用string类的加法以及cout类的setw函数和对string逆序排列。