题目
给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。
示例 1:
输入: num = 100
输出: "202"
示例 2:
输入: num = -7
输出: "-10"
代码
/**
* 504. 七进制数 https://leetcode-cn.com/problems/base-7/
*
* 给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。
*/
public class E504 {
// 1-2 ms.
// public static String convertToBase7(int num) {
//
// if (num == 0) {
// return "0";
// }
//
// String res = "";
// int quotient = Math.abs(num);
//
// while (quotient != 0) {
// res = res.concat(Integer.toString(quotient % 7));
// quotient /= 7;
// }
//
// return (num < 0 ? "-" : "") + new StringBuilder(res).reverse().toString();
// }
public static String convertToBase7(int num) {
return Integer.toString(num,7);
}
public static void main(String[] args) {
System.out.println(convertToBase7(100));
}
}
Integer.toString(int i, int radix)
看一下它的源码,效率确实块。
public static String toString(int i, int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
/* Use the faster version */
if (radix == 10) {
return toString(i);
}
char buf[] = new char[33];
boolean negative = (i < 0);
int charPos = 32;
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = digits[-(i % radix)];
i = i / radix;
}
buf[charPos] = digits[-i];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (33 - charPos));
}
/**
* All possible chars for representing a number as a String
*/
final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
附:测试图
来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/base-7