题解 | #进制转换#
进制转换
http://www.nowcoder.com/practice/2cc32b88fff94d7e8fd458b8c7b25ec1
public class Solution {
/**
* 进制转换
* @param M int整型 给定整数
* @param N int整型 转换到的进制
* @return string字符串
*/
// 因为要考虑到 余数 > 9 的情况,2<=N<=16.
public static final String[] F = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
public String solve (int M, int N) {
// write code here
//要考虑 M 为负数的情况
Boolean flag = false;
if(M < 0) {
flag = true;
M *= -1;
}
StringBuffer sb = new StringBuffer();
int temp;
while(M != 0) {
temp = M % N;
sb.append(F[temp]);
M = M / N;
}
// 字符串反转
sb.reverse();
return (flag ? "-" : "") + sb.toString();
}
}