Description
https://leetcode.com/problems/base-7/
Given an integer num
, return a string of its base 7 representation.
Example 1:
Input: num = 100 Output: "202"
Example 2:
Input: num = -7 Output: "-10"
Constraints:
-107 <= num <= 107
Explanation
Keep dividing num until n < 7, add all remainders. Then finally add the last quotient. If num is negative, add “-” before the result.
Python Solution
class Solution:
def convertToBase7(self, num: int) -> str:
is_negative = False
if num < 0:
num = -num
is_negative = True
result = ""
while num >= 7:
result += str(num % 7)
num = num // 7
result += str(num)
if is_negative:
return "-" + result[::-1]
return result[::-1]
- Time Complexity: O(N).
- Space Complexity: O(N).