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)
  • 相关阅读:
    php intval()函数
    MVC开发模式
    Session详解
    JSP入门
    Response中文乱码问题
    cookie入门
    idea实现更改servlet模板
    使用new和newInstance()创建类的区别
    Servlet 3.0 新特性详解
    web Servlet 3.0 新特性之web模块化编程,web-fragment.xml编写及打jar包
  • 原文地址:https://www.cnblogs.com/bonelee/p/8728741.html
Copyright © 2011-2022 走看看