3249:進制轉換——字符串形式的10進制轉爲2進制

3249:進制轉換:將一個長度最多爲30位數字的十進制非負整數轉換爲二進制數輸出。

思路:用到了大整數類,Big,內嵌一個除2的函數,其他同進制轉換

#include<iostream>
#include<string>
#include<stack>
#include<string.h>
using namespace std;
class Big
{
public:
	int size,digit[35];
	Big(){size=0;memset(digit,0,sizeof(digit));}
	Big StoBig(string s)
	{
		int i;
		for (i=s.length()-1;i>=0;i--)
			digit[size++]=s[i]-'0';
		return *this;
	}
	Big div(int x)
	{
		int i,carry=0;
		Big ans;
		ans.size=size;
		for (i=size-1;i>=0;i--)
		{
			ans.digit[i]=(carry*10+digit[i])/x;
			carry=(carry*10+digit[i])%x;
		}
		if (ans.digit[size-1]==0)	
			ans.size--;
		return ans;
	}
};
int main()
{
	string s;
	Big src,ans;
	int x;
	stack<int> t;
	while(cin>>s)
	{
		src.StoBig(s);
		while(src.size!=0)
		{
			if (src.digit[0]%2==0)
				t.push(0);
			else t.push(1);
			src=src.div(2);
		}
		while(!t.empty())
		{
			x=t.top();t.pop();
			cout<<x;
		}
		cout<<endl;
	}
	return 0;
}

 

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