zl程序教程

您现在的位置是:首页 >  其他

当前栏目

leetcode 504. Base 7

LeetCode base 504
2023-09-14 09:11:53 时间

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

class Solution(object):
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        """
        Input: 100
Output: "202"
100%7=14,2
14%7=2,0
2%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: 100
Output: "202"
100%7=14,2
14%7=2,0
2%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)