LeetCode 504: Base 7 Solution in Python – A Step-by-Step Guide
Imagine you’re an explorer in a world where numbers aren’t in the familiar base 10 but in base 7—where counting goes 1, 2, 3, 4, 5, 6, 10, 11, and so on. Your mission? Take any decimal number, like 100, and transform it into its base-7 form, like "202". That’s the fun challenge of LeetCode 504: Base 7, an easy-level problem that’s perfect for practicing number manipulation in Python. We’ll explore two solutions: the Best Solution, an iterative division method that’s fast and straightforward, and an Alternative Solution, a recursive approach that’s elegant but less common. With detailed examples, clear code, and a friendly tone—especially for the base-7 breakdown—this guide will help you convert numbers like a pro, whether you’re new to coding or brushing up. Let’s dive into the base-7 world and start converting!
What Is LeetCode 504: Base 7?
In LeetCode 504: Base 7, you’re given an integer (positive, negative, or zero), and your task is to convert it to its base-7 representation as a string. Base 7 uses digits 0-6, and each position represents a power of 7 (e.g., 202 in base 7 is 2×7² + 0×7¹ + 2×7⁰ = 100 in base 10). For example, 100 becomes "202", -7 becomes "-10", and 0 is just "0". This problem tests your ability to handle number systems, similar to LeetCode 405: Convert a Number to Hexadecimal, but with a base-7 twist.
Problem Statement
- Input: Integer num.
- Output: String—base-7 representation of num.
- Rules: Handle negatives with a leading "-"; base 7 uses digits 0-6.
Constraints
- -10⁷ <= num <= 10⁷
Examples
- Input: 100
- Output: "202"
- 100 = 2×7² + 0×7¹ + 2×7⁰.
- Input: -7
- Output: "-10"
- -7 = -1×7¹ + 0×7⁰.
- Input: 0
- Output: "0"
- Zero is zero everywhere!
Understanding the Problem: Converting to Base 7
To solve LeetCode 504: Base 7 in Python, we need a function that takes a decimal integer and returns its base-7 string. In base 10, we’re used to powers of 10 (e.g., 123 = 1×10² + 2×10¹ + 3×10⁰), but in base 7, it’s powers of 7. We’ll explore:
- Best Solution (Iterative Division): O(log₇ n) time, O(1) space—fast and practical.
- Alternative Solution (Recursive): O(log₇ n) time, O(log₇ n) space—elegant but uses stack space.
Let’s jump into the iterative solution with a friendly breakdown!
Best Solution: Iterative Division with String Building
Why Iterative Division Is the Best
The iterative division method is the go-to for LeetCode 504 because it’s efficient and intuitive. It mimics how we convert numbers to base 10 by hand—repeatedly divide by 7, collect remainders, and build the string. Time complexity is O(log₇ n) (number of digits in base 7), and space is O(1) (excluding the output string). It’s like peeling off digits one by one to reveal the base-7 secret!
How It Works
Think of this as a number-crunching recipe:
- Step 1: Handle Sign:
- If negative, work with the absolute value and add "-" later.
- Step 2: Divide and Conquer:
- Repeatedly divide by 7, take remainder (0-6), prepend to result.
- Continue until the quotient is 0.
- Step 3: Edge Case:
- If input is 0, return "0".
- Why It Works:
- Remainders give digits from least to most significant.
- Division shrinks the number logarithmically.
It’s like unwrapping a base-7 gift!
Step-by-Step Example
Example: 100
- Init: num = 100, result = "".
- Step 1: Positive, use 100.
- Step 2:
- 100 ÷ 7 = 14, remainder 2 (100 = 14×7 + 2), result = "2".
- 14 ÷ 7 = 2, remainder 0 (14 = 2×7 + 0), result = "02".
- 2 ÷ 7 = 0, remainder 2 (2 = 0×7 + 2), result = "202".
- Quotient = 0, stop.
- Result: "202".
Example: -7
- Init: num = -7, result = "".
- Step 1: Negative, use 7, add "-" later.
- Step 2:
- 7 ÷ 7 = 1, remainder 0 (7 = 1×7 + 0), result = "0".
- 1 ÷ 7 = 0, remainder 1 (1 = 0×7 + 1), result = "10".
- Quotient = 0, stop.
- Step 3: Add sign, result = "-10".
- Result: "-10".
Code with Detailed Line-by-Line Explanation
Here’s the Python code, explained for beginners:
class Solution:
def convertToBase7(self, num: int) -> str:
# Step 1: Handle zero
if num == 0:
return "0"
# Step 2: Handle sign
is_negative = num < 0
num = abs(num) # Work with positive value
result = []
# Step 3: Convert to base 7
while num:
result.append(str(num % 7)) # Remainder as string
num //= 7 # Integer division
# Step 4: Build result
return "-" + "".join(result[::-1]) if is_negative else "".join(result[::-1])
- Lines 4-5: If input is 0, return "0" directly.
- Lines 8-9: Check if negative, use absolute value.
- Line 10: List to collect digits (strings for easy joining).
- Lines 13-15: While num > 0:
- Append remainder (0-6) as string.
- Divide by 7, discard remainder.
- Line 18: Reverse digits (least to most significant), join, add "-" if needed.
- Time Complexity: O(log₇ n)—digits in base 7.
- Space Complexity: O(1)—list size is output, not extra.
It’s like a base-7 digit factory!
Alternative Solution: Recursive Approach
Why an Alternative Approach?
The recursive solution is a stylish twist: break the number into its base-7 parts using recursion. It’s still O(log₇ n) time but uses O(log₇ n) space due to the call stack. It’s less common but great for understanding recursion in Python.
How It Works
Picture this as a number-slicing dance:
- Step 1: Base case—return "0" if num is 0.
- Step 2: Handle sign separately.
- Step 3: Recursively:
- Get remainder (num % 7).
- Recurse on quotient (num // 7), append remainder.
- Step 4: Combine results.
It’s like peeling layers recursively!
Step-by-Step Example
Example: 100
- Call: convert(100):
- 100 % 7 = 2, 100 // 7 = 14.
- convert(14) + "2":
- 14 % 7 = 0, 14 // 7 = 2.
- convert(2) + "0":
- 2 % 7 = 2, 2 // 7 = 0.
- convert(0) = "0" + "2" = "02".
- "02" + "0" = "020".
- "020" + "2" = "0202".
- Trim: "202".
- Result: "202".
Code for Recursive Approach
class Solution:
def convertToBase7(self, num: int) -> str:
# Base case
if num == 0:
return "0"
# Handle sign
if num < 0:
return "-" + self.convertToBase7(-num)
# Recursive case
return self.convertToBase7(num // 7) + str(num % 7) if num > 0 else ""
- Lines 4-5: Base case for 0.
- Lines 8-9: Handle negative by recursing on positive, adding "-".
- Line 12: Recurse on quotient, append remainder.
- Time Complexity: O(log₇ n)—recursion depth.
- Space Complexity: O(log₇ n)—call stack.
It’s a recursive base-7 builder!
Comparing the Two Solutions
- Iterative (Best):
- Pros: O(1) space, straightforward.
- Cons: Manual string building.
- Recursive (Alternative):
- Pros: Elegant, concise.
- Cons: O(log₇ n) space.
Iterative wins for efficiency!
Additional Examples and Edge Cases
- 7: "10"—7¹.
- -100: "-202".
- 1: "1".
Iterative handles them all easily.
Complexity Recap
- Iterative: Time O(log₇ n), Space O(1).
- Recursive: Time O(log₇ n), Space O(log₇ n).
Iterative is the space-saver!
Key Takeaways
- Division: Modulo + divide = base conversion.
- Python: Strings and lists shine—see Python Basics.
- Recursion: Cool but costly.
- Base 7: A fun twist on numbers!
Final Thoughts: Convert to Base 7!
LeetCode 504: Base 7 in Python is a delightful number system challenge. Iterative division is your fast friend, while recursion adds flair. Want more? Try LeetCode 405: Convert a Number to Hexadecimal or LeetCode 168: Excel Sheet Column Title. Ready to convert? Head to Solve LeetCode 504 on LeetCode and transform those numbers today!