描述
Given a decimal number n
and an integer k
, Convert decimal number n
to base-k
.
1.0<=n<=2^31-1
, 2<=k<=16
2.Each letter over 9 is indicated in uppercase
您在真实的面试中是否遇到过这个题?
是
样例
Example 1:
Given n
= 5
, k
= 2
return "101"
Example 2:
Given n
= 30
, k
= 16
return "1E"
入门难度:注意程序鲁棒性
class Solution {
public:
/**
* @param n: a decimal number
* @param k: a Integer represent base-k
* @return: a base-k number
*/
string hexConversion(int n, int k) {
// write your code here
if(n==0) return to_string(0);
string con;
for (int i = 0; n>0; i++) {
if (n%k<10)
con += to_string(n%k);
else {
switch (n%k) {
case 10:con += 'A'; break;
case 11:con += 'B'; break;
case 12:con += 'C'; break;
case 13:con += 'D'; break;
case 14:con += 'E'; break;
case 15:con += 'F'; break;
}
}
n = n / k;
}
reverse(con.begin(), con.end());
return con;
}
};