-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconvertToBase7.go
More file actions
49 lines (40 loc) · 811 Bytes
/
Copy pathconvertToBase7.go
File metadata and controls
49 lines (40 loc) · 811 Bytes
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
/* https://leetcode.com/problems/base-7/#/description
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].
*/
package lmath
import (
"strconv"
"strings"
)
func convertToBase7(num int) string {
if num == 0 {
return "0"
}
reverse := func(chars []string) {
for i := 0; i < len(chars)/2; i++ {
j := len(chars) - i - 1
chars[i], chars[j] = chars[j], chars[i]
}
}
isNegative := false
if num < 0 {
isNegative, num = true, -num
}
var symbols []string
for num > 0 {
symbols = append(symbols, strconv.Itoa(num%7))
num /= 7
}
if isNegative == true {
symbols = append(symbols, "-")
}
reverse(symbols)
return strings.Join(symbols, "")
}