504 base 7

Given an integer, return its base 7 string representation.

Example 1:

1
2
Input: 100
Output: "202"

Example 2:

1
2
Input: -7
Output: "-10"

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

思路

简单的7进制转换,采用短除法即可实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class (object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
isNeg = False
if (num < 0):
num = -num
isNeg = True
elif (num == 0):
return "0"
res = ""
while (num):
tmp = num % 7
res = str(tmp) + res
num = num / 7
if (isNeg):
return "-" + res
else:
return res