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;
}

猜你喜欢

转载自blog.csdn.net/Always_ease/article/details/82526648