Given an integer, return its base 7 string representation.
Example 1:
Input: 100Output: "202"
Example 2:
Input: -7Output: "-10"
Note: The input will be in range of [-1e7, 1e7].
class Solution(object): def convertToBase7(self, num): """ :type num: int :rtype: str """ """ Input: 100Output: "202"100%7=14,214%7=2,02%7=2,xxx """ is_neg = False if num < 0: num = -num is_neg = True ans = "" while num >= 7: ans = str(num%7) + ans num = num/7 ans = str(num) + ans return ans if not is_neg else "-"+ans
or
class Solution(object): def convertToBase7(self, num): """ :type num: int :rtype: str """ """ Input: 100Output: "202"100%7=14,214%7=2,02%7=2,xxx """ if num == 0: return '0' is_neg = False if num < 0: num = -num is_neg = True ans = "" while num != 0: ans = str(num%7) + ans num = num/7 return ans if not is_neg else "-"+ans
使用递归:
class Solution(object): def convertToBase7(self, num): """ :type num: int :rtype: str """ if num < 0: return "-"+self.convertToBase7(-num) if num < 7: return str(num) return self.convertToBase7(num/7) + str(num%7)