#504

Base 7

Easy
MathStringMathString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a more efficient method of converting the number to base 7 by directly calculating the digits without unnecessary string operations. This reduces both time and space complexity.

⚙️

Algorithm

5 steps
  1. 1Step 1: Handle the special case where num is 0 and return '0'.
  2. 2Step 2: Determine if the number is negative and store the sign.
  3. 3Step 3: Use a loop to divide the number by 7, collecting remainders in a list.
  4. 4Step 4: Reverse the list of digits to form the correct base 7 representation.
  5. 5Step 5: Convert the list to a string and prepend the sign if necessary.
solution.py15 lines
1# Full working Python code
2
3def base7(num):
4    if num == 0:
5        return '0'
6    sign = ''
7    if num < 0:
8        sign = '-'
9        num = -num
10    digits = []
11    while num > 0:
12        digits.append(str(num % 7))
13        num //= 7
14    return sign + ''.join(reversed(digits))
15

Complexity note: The time complexity is O(n) because we are processing each digit of the number once. The space complexity is O(n) due to storing the digits in a list before converting them to a string.

  • 1Understanding base conversion is crucial for many programming tasks.
  • 2Handling negative numbers requires careful consideration of the sign.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.