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].
不停除以7, 然后把余数放到ans里面, 最后reverse ans加上符号即可.
Code
class Solution:
def convertToBase7(self, num):
if num == 0: return ''
pos = "-" if num < 0 else ""
num, ans = abs(num), ''
while num > 0:
rem, num = divmod(num, 7)
ans += str(num)
num = rem
return pos + ans[::-1]