Environment: Python 3.7

Key technique: divmod function

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

Analysis:

Use divmod function to find quotient and remainder dividing by 7. The 10 Base convert to 7 Base number is as below.

Therefore, the process example is as below.

We also need consider negative case.

Solution:

class Solution(object):
def convertToBase7(self, num):
ans = ''
if num == 0:
return '0'
neg = False
if num < 0:
num = abs(num)
neg = True
c = 0
while num:
num, c = divmod(num, 7)
ans = str(c) + ans
if neg is True:
return '-' + ans
return ans

Reference:

https://blog.csdn.net/NXHYD/article/details/72478883

Interesting in any computer science.