[leetcode]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].

难度

Easy

方法

num取除以7的余数,即为最低位的数,然后将num/7赋值给num,继续取num除以7的余数即为倒数第二位的数,依次类推。注意num0时需要返回"0"

python代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "0"
symbol = ""
if num < 0:
num = 0 - num
symbol = "-"

result = ""
while num > 0:
result += str(num % 7)
num = num / 7

return symbol + result[::-1]

assert Solution().convertToBase7(100) == "202"
assert Solution().convertToBase7(-7) == "-10"