Base 7
Question
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].
Tags
- Mathematics
Thought
Be careful the processes of converting from other base to decimal number and converting from the decimal number to other base are different! Suggest to use string.
Code
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
absValue = abs(num)
sig = num / absValue
ans = ''
while absValue:
ans = str(absValue % 7) + ans
absValue /= 7
if sig < 0:
return '-' + ans
else:
return ans