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)
标签:num,neg,self,Base,str,ans,return,504,leetcode From: https://blog.51cto.com/u_11908275/6381004