题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/0337e32b1e5543a19fa380e36d9343d7
#include <bits/stdc++.h>
#include <bits/types/struct_tm.h>
#include <string>
using namespace std;
// 字符串做除发, 跟手写除法类似, 首先从字符左边一直到右边。 分为两种情况:1.能被x整除,那么就直接得到除数,2.否则不能整除,需要在把模数求得的数*10 + 当前的数 再除。
void divid ( string & s, int x) {
// if()
int rem = 0 ;
for (int i = 0 ; i < s.size() ; ++ i) { // 做除法
int t = rem * 10 + s[i] - '0' ;
s[i] = t / x + '0';
rem = t % x; // t
}
int pos = 0 ;
while(s[pos] == '0')
{
pos++ ;
}
// cout<< "pos"<<pos <<endl ;
// if(pos)
// if(pos >= s.size())
// {
// return string() ;
// }
// cout<<"s.substr(pos).size() "<<s.substr(pos).size() <<endl;
s= s.substr(pos) ; // 为避免有前置0, 找到第一个不为0
// 的
}
int main() {
string tmp ;
vector<int> res;
while (cin >> tmp) {
res.clear() ;
if(tmp.size() == 1 &&tmp[0] == '0')
{
return 0 ;
}
while (tmp.size()) {
int last = tmp[tmp.size() - 1] - '0' ;
res.push_back(last % 2 )
; // 整个数对某个数(不超过10)取余相当于最后一位对某个数取余。
divid(tmp, 2) ;
}
for (int i = res.size() - 1; i >= 0 ; --i) {
cout << res[i];
}
cout << endl ;
}
}
// 64 位输出请用 printf("%lld")
查看12道真题和解析
