504. Base 7

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和堆栈,代码如下:

 1 class Solution {
 2     public String convertToBase7(int num) {
 3         Stack<Integer>stack = new Stack<Integer>();
 4         boolean isNagative = false;
 5         if(num < 0){
 6             isNagative = true;
 7             num = -num;
 8         }
 9         while(num != 0){
10             stack.push(num % 7);
11             num /= 7;
12         }
13         StringBuffer result = new StringBuffer("");
14         
15         while(!stack.isEmpty()) result.append(String.valueOf(stack.pop()));
16         if(result.length() == 0) 
17             return String.valueOf(0);
18         else if(isNagative)
19             return '-'+result.toString();
20         else return result.toString();
21     }
22 }

稍微改进一下,去掉栈和StringBuffer,直接使用String及其性质,速度会快很多,代码如下:

 1 class Solution {
 2     public String convertToBase7(int num) {
 3         boolean isNagative = false;
 4         String result = "";
 5         if(num < 0){
 6             isNagative = true;
 7             num = -num;
 8         }
 9         while(num != 0){
10             result = String.valueOf(num % 7) + result;
11             num /= 7;
12         } 
13         if(result.length() == 0) 
14             return String.valueOf(0);
15         else if(isNagative)
16             return '-'+result;
17         else return result;
18     }
19 }

当然也可以这样,虽然有点投机取巧:

1  public String convertToBase7(int num) {
2         return Integer.toString(num, 7);
3  }

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9168181.html