763. 进制转换
给定一个十进制数
n
和 一个整数
k
, 将
十进制数 n
转换成
k进制数
.
样例
样例 1:
输入 : n = 5, k = 2
输出 : 101
样例 2:
输入 : n = 30, k = 16
输出 : "1E"
注意事项
-
0<=n<=2^31-1 , 2<=k<=16
-
Each letter over 9 is indicated in uppercase
public class Solution {
/**
* @param n: a decimal number
* @param k: a Integer represent base-k
* @return: a base-k number
*/
public String hexConversion(int n, int k) {
// write your code here
switch (k) {
case 16:
return Integer.toHexString(n).toUpperCase();
case 8:
return Integer.toOctalString(n);
case 2:
return Integer.toBinaryString(n);
case 10:
return n + "";
}
StringBuilder ret = new StringBuilder();
if (k > 9) {
int sum = k * k;
while (sum < n) {
sum = sum * k;
}
while (k < sum) {
sum = sum / k;
int temp=n / sum;
if (temp>9){
ret.append(Integer.toHexString(temp).toUpperCase());
}else {
ret.append(temp);
}
n = n % sum;
}
ret.append(n);
} else {
int sum = k * k;
while (sum < n) {
sum = sum * k;
}
while (k < sum) {
sum = sum / k;
ret.append(n / sum);
n = n % sum;
}
ret.append(n);
}
return ret.toString();
}
}