Problem
Given an integer num, return a string of its base 7 representation.
Algorithm
Distinguish between positive and negative values, then store the remainders in reverse order after dividing by 7.
Code
class Solution:
def convertToBase7(self, num: int) -> str:
if not num:
return "0"
sign = 0
if num < 0:
num = -num
sign = -1
ans = ""
while num:
ans = str(num % 7) + ans
num //= 7
if sign < 0:
ans = "-" + ans
return ans