题解 | #进制转换#

进制转换

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

模拟手工除法的过程
#include<vector>
#include<string>
#include<iostream>
#include<cstdio>
using namespace std;

string Divide(string str, int x) {   // 模拟手工计算除以2的过程
	int remainder = 0;
	for (int i = 0; i < str.size(); i++) {
		 //如果某一位无法被整除 便保留其除以除数的余数,余数乘以十和低一位一起加入计算
		int temp = remainder * 10 + str[i] -'0';
		str[i] = temp / x + '0';
		remainder = temp % x;
	
	}
	int pos = 0;
	while (str[pos] == '0') {
		pos++;
	}

	str = str.substr(pos);
	return str;
}



int main() {
	string str;
	vector<int> vec;
	while (cin >> str) {
		if (str == "0") {
            cout << "0"<<endl;
            continue;
        }
		vec.clear();
		while (str != "") {  //str不等于空串的时候
			vec.push_back((str[str.size() - 1] - '0') % 2);
			str = Divide(str, 2);
		}
		for (int i = vec.size() - 1; i >= 0; i--) {
			cout << vec[i];

		}
		cout << endl;


	}



}

全部评论

相关推荐

点赞 评论 收藏
分享
小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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