[LeetCode]504. Base 7

2017-08-22  本文已影响24人  Eazow

题目

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

难度

Easy

方法

num取除以7的余数,即为最低位的数,然后将num/7赋值给num,继续取num除以7的余数即为倒数第二位的数,依次类推。注意num0时需要返回"0"

python代码

class Solution(object):
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0:
            return "0"
        symbol = ""
        if num < 0:
            num = 0 - num
            symbol = "-"

        result = ""
        while num > 0:
            result += str(num % 7)
            num = num / 7

        return symbol + result[::-1]

assert Solution().convertToBase7(100) == "202"
assert Solution().convertToBase7(-7) == "-10"
上一篇 下一篇

猜你喜欢

热点阅读