PU Base 7

Jan 01, 1970

Given an integer, return its base 7 string representation.

  • The input will be in range of [-1e7, 1e7].

Example 1:

  • Input: 100
  • Output: "202"

Example 2:

  • Input: -7
  • Output: "-10"

Python Solution:

class Solution(object):
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0: return "0"
        if num < 0: return '-' + self.convertToBase7(-num)
        res = []
        while num:
            res.append(str(num % 7))
            num //= 7
        res = "".join(res[::-1])
        return res

Summary:

  • recursive makes the code much more concise.

LeetCode: 504. Base 7