题解 | #进制转换2#
进制转换2
https://www.nowcoder.com/practice/ae4b3c4a968745618d65b866002bbd32
#include <iostream> #include <string> using namespace std; int char2int(char in) { if(in >= '0' && in <= '9') { return in - '0'; } else { return in - 'A' + 10; } } char int2char(int in) { if(in >= 0 && in <= 9) { return in + '0'; } else { return in - 10 + 'A'; } } // 逻辑很简单:每一位是(c*M + it) / N,商为该位新值,余数为下一位的退位c; // 最后输出余数c,并清除头部所有的0 char divide(string& in_M, int& M, string& out_N, int& N) { int c = 0, tmp; for(auto it = in_M.begin(); it != in_M.end(); ++it) { tmp = char2int(*it) + c * M; *it = int2char(tmp / N); c = tmp % N; } while(in_M[0] == '0') { in_M.erase(in_M.begin()); } return int2char(c); } int main() { int M, N; while (cin >> M >> N) { string in_M; cin >> in_M; string out_N; while(in_M.size() != 0) { // 从最小到最大倒序输出新位数,所以头插输出串 out_N.insert(out_N.begin(), divide(in_M, M, out_N, N)); } cout << out_N << endl; } } // 64 位输出请用 printf("%lld")