[
math
]
Leetcode 0504 Base 7
Problem statement
https://leetcode.com/problems/base-7/
Solution
Just divide number by seven end evaluate reminder. Also handle negative numbers cases.
Complexity
Complexity is O(log n)
, both time and space, we need to do this number of divisions.
Code
class Solution:
def convertToBase7(self, num):
sgn = 1 if num < 0 else 0
ans, num = "", abs(num)
while num:
num, digit = divmod(num, 7)
ans += str(digit)
return "-"*sgn + ans[::-1] if ans else "0"