Skip to content

Latest commit

 

History

History
95 lines (51 loc) · 1.18 KB

0504._Base_7.md

File metadata and controls

95 lines (51 loc) · 1.18 KB

504. Base 7

难度: Easy

刷题内容

原题连接

内容描述

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].

解题方案

思路 1 - 时间复杂度: O(log(num, 7))- 空间复杂度: O(1)******

迭代

class Solution:
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0: 
            return '0'
        n, res = abs(num), ''
        while n:
            res = str(n % 7) + res
            n //= 7
        return res if num > 0 else '-' + res

思路 2 - 时间复杂度: O(log(num, 7))- 空间复杂度: O(1)******

递归

class Solution:
    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)