Given an integer, return its base 7 string representation. Example 1: Input: 100
Output: "202" Example 2: Input: -7
Output: "-10" Note: The input will be in range of [-1e7, 1e7].
解题:题意很容易理解,将十进制整型数转化为七进制的数,并以字符串的形式返回。先看我写的第一种方法,比较繁琐,也利用了StringBuffer和堆栈,代码如下:
class Solution {
public String convertToBase7(int num) {
Stack<Integer>stack = new Stack<Integer>();
boolean isNagative = false;
if(num < 0){
isNagative = true;
num = -num;
}
while(num != 0){
stack.push(num % 7);
num /= 7;
}
StringBuffer result = new StringBuffer(""); while(!stack.isEmpty()) result.append(String.valueOf(stack.pop()));
if(result.length() == 0)
return String.valueOf(0);
else if(isNagative)
return '-'+result.toString();
else return result.toString();
}
}
稍微改进一下,去掉栈和StringBuffer,直接使用String及其性质,速度会快很多,代码如下:
class Solution {
public String convertToBase7(int num) {
boolean isNagative = false;
String result = "";
if(num < 0){
isNagative = true;
num = -num;
}
while(num != 0){
result = String.valueOf(num % 7) + result;
num /= 7;
}
if(result.length() == 0)
return String.valueOf(0);
else if(isNagative)
return '-'+result;
else return result;
}
}
当然也可以这样,虽然有点投机取巧:
public String convertToBase7(int num) {
return Integer.toString(num, 7);
}