[LeetCode] 504. Base 7_Easy tag: Math
2018-08-20 08:47 Johnson_强生仔仔 阅读(178) 评论(0) 编辑 收藏 举报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 '0' 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]