題目
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].
難度
Easy
方法
對num
取除以7
的余數,即為最低位的數,然后將num/7
賦值給num
,繼續取num
除以7
的余數即為倒數第二位的數,依次類推。注意num
為0
時需要返回"0"
python代碼
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"