GuoXin Li's Blog

LeetCode504. Base 7

字数统计: 199阅读时长: 1 min
2020/02/29 Share

504. Base 7

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].

Resolution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public String convertToBase7(int num) {
StringBuilder com = new StringBuilder();
if(num == 0) return "0";
boolean flag = num < 0;
num = Math.abs(num);
while(num != 0){
com.append(num % 7);
num = num/7;
}
StringBuilder com_ = com.reverse();
String str = com_.toString();
return flag ? "-"+str : str;
}
}

Time Complexity: O(logn)

Space Complexity: O(logn)

note:

important: num.toString( ); ——> wrong. Object numberdo not has the method “toString( )”

don’t foget to check the initial condition firstly.

A good solution of java Integer

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

C++ solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string convertToBase7(int num) {
string ans;
bool is_nagetive = num < 0;
num = abs(num);
do{
ans = std::to_string(num%7) + ans;
num /=7;
}while(num > 0);
if(is_nagetive){
return "-"+ans;
}
return ans;
}
};

key:implicit handle of special case 0 —>> using do{ }while( );

Time Complexity: O(logn)

Space Complexity: O(logn)

CATALOG
  1. 1. 504. Base 7
  2. 2. Example 1:
  3. 3. Resolution
  4. 4. A good solution of java Integer
  5. 5. C++ solution