牛客网 KY30 进制转换

思路

对输入字符串对2取模再除以2,对于字符串取模运算,转换为对字符串最低位数进行取模;字符串除法则是把字符串从高到低逐位除以除数,如果不能整除,那么保留它除以除数的余数,余数乘10后和低位相加后一起处理,由于有前置0,故应取首个非0位之后的字符。

程序代码

#include <iostream>
#include <vector>
using namespace std;

int qu_yu(string a) {			//取余

	return (a[a.length() - 1] - '0') % 2;

}

void zi_fu_chuan_chu_fa(string& a) {		//字符串除法
	int temp = 0;
	int i = 0;
	while (a[i] == '0') {
		++i;
	}
	for (; i < a.length(); ++i) {
		int x = (a[i]-'0') + temp;
		a[i] = (x / 2) + '0';
		temp = x % 2 * 10;
	}

}

int main()
{
	string ss;
	while (cin >> ss) {
		vector<int> re;
		if (ss == "0") 
			re.push_back(0);
		else {
			bool t = true;
			while (t) {
				re.push_back(qu_yu(ss));
				zi_fu_chuan_chu_fa(ss);
				for (int i = 0; i < ss.length(); ++i) {				//看字符串是否为全0
					if (ss[i] != '0') break;
					if ((i == ss.length() - 1) && ss[i] == '0') t = false;
				}
			}
		}

		for (int i = re.size()-1; i>=0; --i) {
			cout << re[i];
		}

		cout << endl;

	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值