-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathbase-7.py
123 lines (105 loc) · 2.75 KB
/
base-7.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""
504. Base 7
Easy
Given an integer num, return a string of its base 7 representation.
Example 1:
Input: num = 100
Output: "202"
Example 2:
Input: num = -7
Output: "-10"
Constraints:
-107 <= num <= 107
"""
# V0
# IDEA : MATH : 10 based -> 7 based
class Solution(object):
def convertToBase7(self, num):
# help fumc
def help(x):
x = int(x)
res = ""
while x:
a, b = divmod(x, 7)
x = a
res += str(b)
return res[::-1]
"""
# if positvie, based 10 -> based 7
# if negative, move - away, do based 10 -> based 7, then add - back
"""
# edge case
if num == 0:
return "0"
minus = False
if num < 0:
num = abs(num)
minus = True
_res = help(num)
return _res if not minus else "-" + _res
# V0'
# IDEA : MATH : 10 based -> 7 based
"""
### NOTE :
1) for negative num : transform to positive int first, do 10 based -> 7 based op
then add "-" at beginning
2) for positive num : do 10 based -> 7 based op
-> keep checking if num % N == 0
-> if not == 0, keep do num = num % N, and append cur result to res
-> reverse res
-> make array to string
-> return result
3) example:
100 (10 based) -> "202" (7 based)
tmp = 100
a, b = divmod(tmp, 7) -> a = 14, b = 2, tmp = 14
a, b = divmod(tmp, 7) -> a= 2, b = 0, tmp = 2
a, b = divmod(tmp, 7) -> a = 0, b = 2
-> so res = [2,0,2]
"""
class Solution(object):
def convertToBase7(self, num):
# edge case
if num == 0:
return '0'
tmp = abs(num)
res = []
while tmp > 0:
a, b = divmod(tmp, 7)
res.append(str(b))
tmp = a
res = res[::-1]
_res = "".join(res)
if num > 0:
return _res
else:
return "-" + _res
# V1
# https://www.itread01.com/content/1544603062.html
# https://kknews.cc/code/jlv38qp.html
class Solution(object):
def convertToBase7(self, num):
# edge case
if num == 0:
return '0'
tmp = abs(num)
res = []
while tmp:
i = tmp % 7
res.append(str(i))
tmp = tmp // 7
res = res[::-1]
_res = "".join(res)
if num > 0:
return _res
else:
return "-" + _res
# V1'
# https://kknews.cc/code/jlv38qp.html
# IDEA : JAVA
# class Solution {
# public String convertToBase7(int num) {
# return Integer.toString(num, 7);
# }
# }
# V2