[leetcode] problem 504 – base 7

Given an integer, return its base 7 string representation.

Example

No.1

Input: 100

Output: “202”

No.2

Input: -7

Output: “-10”

Note

The input will be in range of [-1e7, 1e7].

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public String (int num) {
if (num == 0)
return "0";

StringBuilder sb = new StringBuilder();
boolean positive = num >= 0;
num = Math.abs(num);

while (num > 0) {
sb.append(num % 7);
num /= 7;
}

String result = sb.reverse().toString();
return positive ? result : "-" + result;
}