C++进制转换
进制转化的题经常出现,每次都要手动模拟一下很耽误时间,总结一下模板以后就不想了
2-36任意进制转换为10进制
typedef long long ll;
ll Atoi(string s, int r) {
ll ans = 0;
for (int i = 0; i < s.size(); i ++) {
if (isdigit(s[i])) ans = ans*r + s[i]-'0';
else ans = ans*r + (s[i]-'A'+10);
}
return ans;
}
将10进制数转换为任意的n进制数
typedef long long ll;
string Itoa(ll n, int r) {
string ans;
do {
ll x = n % r;
if (x >= 0 && x <= 9) ans += x + '0';
else ans += x - 10 + 'A';
n /= r;
} while (n); // 为了防止n=0的情况出现,采用do-while结构,注意while要加;
reverse(ans.begin(), ans.end());
return ans;
}