题解 | #进制转换#

进制转换

https://www.nowcoder.com/practice/0337e32b1e5543a19fa380e36d9343d7

#include<iostream>
#include<vector>
#include<string>
using namespace std;
//只适合小于10进制转小于10进制的数 
string divide(string str,int x)
{
	int remain=0;
	for(int i=0;i<str.size();i++)
	{
		int current=remain*10+str[i]-'0';//上一个数的余数加本身 
		str[i]=current/x+'0';//这位÷2应该是几
		remain=current%x;  //这位数%2的余数在下一位用上 
		//将字符串除以2 
	}
	int pos=0;
	while(str[pos]=='0')
	pos++;
	return str.substr(pos);//substr(pos)截取函数 下标为0为第一个字符 截取pos之后的字符 
	//返回除以2以后的数 
}
int main()
{
	string str;
	while(cin>>str)
	{
		
		vector<int> bi;
		while(str.size()!=0)
		{
			int last=str[str.size()-1]-'0';
			bi.push_back(last%2);//模2 
			str=divide(str,2);//除以2 
		}
		for(int i=bi.size()-1;i>-1;i--)//逆序输出 
		{
			printf("%d",bi[i]);
		}
		printf("\n");
		
	}
	return 0;
}




全部评论

相关推荐

对空六翼:你真幸运,碰见这么好的人,不像我,秋招的时候被室友骗进cx了
实习好累,可以辞职全力准...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务