C++ 使用简单方法输出整形的31位二进制

总时间限制: 

1000ms

内存限制: 

65536kB

// 在此处补充你的代码

描述

给出一个int表示范围内的正整数x,输出其二进制表示。一共要输出31位,不足处要补0。

#include <iostream>
#include <string>
using namespace std;
string dec2bin(int x){
}
int main(){
	int n;
	cin >> n;
	while(n--) {
		int x;
		cin >> x;
		cout << dec2bin(x) << endl;
	}
	return 0;
}

输入

第一行是整数n(n<15),表示有n个正整数要处理
第二行是n个正整数

输出

对每个给出的正整数,输出其二进制表示。不足31位则用0补齐到31位

样例输入

3
1 2 3

样例输出

0000000000000000000000000000001
0000000000000000000000000000010
0000000000000000000000000000011

这里用的算法就是除k取余数,输出的时候要倒序输出,适应了C++ string的拼接方式,最后的补零操作也是这么做的

#include <iostream>
#include <string>
using namespace std;
string dec2bin(int x)
{
	// 在此处补充你的代码
	string s = "";
	string s1;
	while (x)
	{
		if (x % 2)
		{
			s1 = "1";
		}
		else
		{
			s1 = "0";
		}
		x = x / 2;
		s = s1 + s;
	}
	for (int i = s.size(); i < 31; i++)
	{
		s = "0" + s;
	}
	return s;

}
int main() {
	int n;
	cin >> n;
	while (n--) {
		int x;
		cin >> x;
		cout << dec2bin(x) << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/83959702
今日推荐