forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBase7.java
55 lines (47 loc) · 1.07 KB
/
Base7.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package leetcode;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : Base7
* Creator : Edward
* Date : Nov, 2017
* Description : 504. Base 7
*/
public class Base7 {
/**
* Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
time : O(n)
space : O(n)
*/
public String convertToBase7(int num) {
if (num == 0) return "0";
StringBuilder sb = new StringBuilder();
boolean negative = false;
if (num < 0) {
negative = true;
}
while (num != 0) {
sb.append(Math.abs(num % 7));
num = num / 7;
}
if (negative) {
sb.append("-");
}
return sb.reverse().toString();
}
public String convertToBase72(int num) {
if (num < 0) {
return "-" + convertToBase72(-num);
}
if (num < 7) {
return num + "";
}
return convertToBase72(num / 7) + num % 7;
}
}