### View *Base 7* on LeetCode

## Statistics

**Time Complexity**

O(n) - The algorithm traverses each element from the list (n), trumping the log base-7 time complexity of the mathematical conversion, resulting in the O(n) time complexity.

**Space Complexity**

O(n) - The algorithm must accurately convert the input number to base 7, taken to have `n`

numbers, resulting in the O(n) space complexity.

**Runtime Beats**

82.66% of other submissions

**Memory Beats**

95.72% of other sumbissions

## Explanation

Before converting, create a list to contain the converted number, eliminate the base case (num = 0), and store the correct sign of the result.

Begin iteratively dividing the input number by the new base (7) and append its remainder to the converted list.

Once the number is less than or equal to 0, return the combination of the sign and the number (in string representation).

*Since the converted number is being created by appending to a list, each number appended is in reverse order. To correct this, join the list in reverse ([::-1]).*

## Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

class Solution:
def convertToBase7(self, num: int) -> str:
s = []
if num == 0: return "0"
sign = ''
if num < 0:
sign = '-'
num = -num
while num > 0:
s.append(str(num%7))
num //= 7
return sign + ''.join(s[::-1])