zoukankan      html  css  js  c++  java
  • leetcode 504. Base 7

    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)
  • 相关阅读:
    BZOJ 5018 [Snoi2017]英雄联盟
    BZOJ 4945 [Noi2017]游戏
    BZOJ4942 [Noi2017]整数
    BZOJ 2427 [HAOI2010]软件安装
    BZOJ 4870 [Shoi2017]组合数问题
    THINKPHP 全局404
    PHP 万能查询代码
    xml Array 相互转化
    JS 倒计时计算
    PHP 多态
  • 原文地址:https://www.cnblogs.com/bonelee/p/8728741.html
Copyright © 2011-2022 走看看