程序设计与算法(三)期末考试之001:编程填空:二进制输出

001:编程填空:二进制输出

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

#include <iostream>
#include <string>
using namespace std;
string dec2bin(int x){
string strres;
	for(int i=0;i<31;i++)
	{
		if(x%2==0)
		{
			strres="0"+strres;
		}
		else
		{
			strres="1"+strres;
		}
		x=x/2;
	}
	return strres;
}
int main(){
	int n;
	cin >> n;
	while(n--) {
		int x;
		cin >> x;
		cout << dec2bin(x) << endl;
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章