504. Base 7
Problem Description
This problem asks you to convert a given integer into its base 7 representation and return it as a string.
In base 7 numbering system, we only use digits 0 through 6 to represent numbers. Each position represents a power of 7, similar to how base 10 uses powers of 10.
For example:
- The number
100
in base 10 would be202
in base 7 because:100 = 2×7² + 0×7¹ + 2×7⁰ = 2×49 + 0×7 + 2×1
- The number
7
in base 10 would be10
in base 7 - The number
-7
in base 10 would be-10
in base 7
The solution handles three cases:
- If
num
is 0, it directly returns'0'
- If
num
is negative, it recursively converts the positive value and prepends a minus sign - For positive numbers, it repeatedly divides by 7, collecting remainders which form the digits of the base 7 representation (in reverse order), then reverses them to get the final result
The algorithm works by:
- Taking the remainder when dividing by 7 (this gives the rightmost digit in base 7)
- Integer dividing by 7 to shift to the next position
- Repeating until the number becomes 0
- Reversing the collected digits since they were gathered from right to left
Intuition
The key insight comes from understanding how number systems work. In any base system, a number can be broken down into digits by repeatedly dividing by the base and keeping track of remainders.
Think about how we normally extract digits from a decimal number. To get the last digit of 123
, we can do 123 % 10 = 3
. To get the second-to-last digit, we first remove the last digit by doing 123 // 10 = 12
, then take 12 % 10 = 2
. This same principle applies to any base conversion.
When converting to base 7, each remainder when dividing by 7 tells us what digit should appear at that position. The reason we use modulo (%
) operation is that it gives us exactly the value that "doesn't fit" into groups of 7, which becomes our digit for that position.
For example, if we have 100
:
100 % 7 = 2
(this is our rightmost digit)100 // 7 = 14
, then14 % 7 = 0
(this is our middle digit)14 // 7 = 2
, then2 % 7 = 2
(this is our leftmost digit)2 // 7 = 0
(we stop here)
Reading the remainders in reverse gives us 202
in base 7.
The handling of negative numbers is straightforward - we can convert the positive version and just add a negative sign, since the digit representation itself follows the same pattern regardless of sign. The special case for zero is needed because the while loop wouldn't execute at all for zero, so we handle it explicitly.
Learn more about Math patterns.
Solution Approach
The implementation uses a recursive approach combined with iterative digit extraction:
-
Base Cases Handling:
- If
num == 0
, immediately return'0'
since zero is represented as '0' in any base - If
num < 0
, recursively call the function with the positive value-num
and prepend a minus sign to the result
- If
-
Digit Extraction Process:
- Initialize an empty list
ans
to collect the base 7 digits - Use a while loop that continues as long as
num > 0
- In each iteration:
- Calculate
num % 7
to get the current rightmost digit in base 7 - Convert this digit to string and append to
ans
- Update
num
tonum // 7
to remove the processed digit and shift to the next position
- Calculate
- Initialize an empty list
-
Result Construction:
- The digits collected in
ans
are in reverse order (rightmost digit first) - Use
ans[::-1]
to reverse the list - Join all digits with
''.join()
to form the final string
- The digits collected in
Example Walkthrough with num = 100
:
- First iteration:
100 % 7 = 2
, append '2',num = 100 // 7 = 14
- Second iteration:
14 % 7 = 0
, append '0',num = 14 // 7 = 2
- Third iteration:
2 % 7 = 2
, append '2',num = 2 // 7 = 0
- Loop ends,
ans = ['2', '0', '2']
- Reverse and join:
'202'
The algorithm has O(log₇n) time complexity since we divide by 7 in each iteration, and O(log₇n) space complexity for storing the digits.
Ready to land your dream job?
Unlock your dream job with a 3-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through converting the number 50
from base 10 to base 7.
Step-by-step process:
Starting with num = 50
and an empty list ans = []
:
Iteration 1:
- Calculate remainder:
50 % 7 = 1
- This gives us the rightmost digit in base 7
- Append '1' to ans:
ans = ['1']
- Update num:
50 // 7 = 7
Iteration 2:
- Calculate remainder:
7 % 7 = 0
- This gives us the next digit (moving left)
- Append '0' to ans:
ans = ['1', '0']
- Update num:
7 // 7 = 1
Iteration 3:
- Calculate remainder:
1 % 7 = 1
- This gives us the leftmost digit
- Append '1' to ans:
ans = ['1', '0', '1']
- Update num:
1 // 7 = 0
Final Step:
- Since
num = 0
, the loop ends - We have
ans = ['1', '0', '1']
(collected from right to left) - Reverse the list:
['1', '0', '1']
- Join into string:
'101'
Verification:
50 = 1×7² + 0×7¹ + 1×7⁰ = 1×49 + 0×7 + 1×1 = 49 + 0 + 1 = 50
✓
Therefore, 50
in base 10 equals 101
in base 7.
Solution Implementation
1class Solution:
2 def convertToBase7(self, num: int) -> str:
3 """
4 Convert a decimal number to its base-7 representation.
5
6 Args:
7 num: An integer to be converted to base-7
8
9 Returns:
10 A string representing the number in base-7
11 """
12 # Handle the special case of zero
13 if num == 0:
14 return '0'
15
16 # Handle negative numbers by converting the positive value
17 # and prepending a minus sign
18 if num < 0:
19 return '-' + self.convertToBase7(-num)
20
21 # List to store the base-7 digits in reverse order
22 digits = []
23
24 # Extract base-7 digits using repeated division by 7
25 while num > 0:
26 # Get the remainder (current digit in base-7)
27 digits.append(str(num % 7))
28 # Integer division to process the next digit
29 num //= 7
30
31 # Reverse the digits list and join to form the final string
32 # Since we collected digits from least to most significant,
33 # we need to reverse the order
34 return ''.join(reversed(digits))
35
1class Solution {
2 /**
3 * Converts a decimal integer to its base-7 representation as a string.
4 *
5 * @param num The decimal integer to convert (can be positive, negative, or zero)
6 * @return The base-7 representation of the input number as a string
7 */
8 public String convertToBase7(int num) {
9 // Handle the special case where input is 0
10 if (num == 0) {
11 return "0";
12 }
13
14 // Handle negative numbers by converting the positive value and prepending "-"
15 if (num < 0) {
16 return "-" + convertToBase7(-num);
17 }
18
19 // Build the base-7 representation digit by digit
20 StringBuilder result = new StringBuilder();
21
22 // Extract digits from least significant to most significant
23 while (num != 0) {
24 // Get the remainder when dividing by 7 (the rightmost digit in base-7)
25 result.append(num % 7);
26
27 // Remove the rightmost digit by integer division
28 num /= 7;
29 }
30
31 // Reverse the string since we built it from right to left
32 return result.reverse().toString();
33 }
34}
35
1class Solution {
2public:
3 string convertToBase7(int num) {
4 // Handle special case: zero
5 if (num == 0) {
6 return "0";
7 }
8
9 // Handle negative numbers by converting positive part and adding minus sign
10 if (num < 0) {
11 return "-" + convertToBase7(-num);
12 }
13
14 // Build the base-7 representation
15 string result = "";
16
17 // Extract digits from least significant to most significant
18 while (num > 0) {
19 // Get the remainder when divided by 7 (current digit in base 7)
20 int digit = num % 7;
21
22 // Prepend the digit to build the result from right to left
23 result = to_string(digit) + result;
24
25 // Move to the next higher position by dividing by 7
26 num /= 7;
27 }
28
29 return result;
30 }
31};
32
1/**
2 * Converts a decimal number to its base-7 representation
3 * @param num - The decimal number to convert
4 * @returns The base-7 representation as a string
5 */
6function convertToBase7(num: number): string {
7 // Handle the special case of zero
8 if (num === 0) {
9 return '0';
10 }
11
12 // Initialize the result string
13 let result: string = '';
14
15 // Check if the number is negative
16 const isNegative: boolean = num < 0;
17
18 // Work with the absolute value for conversion
19 if (isNegative) {
20 num = -num;
21 }
22
23 // Convert to base-7 by repeatedly dividing by 7
24 while (num !== 0) {
25 // Get the remainder when divided by 7 (current digit in base-7)
26 const remainder: number = num % 7;
27
28 // Prepend the digit to the result string
29 result = remainder + result;
30
31 // Update num to the quotient for the next iteration
32 num = Math.floor(num / 7);
33 }
34
35 // Add negative sign if the original number was negative
36 return isNegative ? '-' + result : result;
37}
38
Time and Space Complexity
Time Complexity: O(log₇(n))
where n
is the absolute value of the input number.
The algorithm repeatedly divides the number by 7 until it becomes 0. The number of iterations required is equal to the number of digits in the base-7 representation, which is ⌊log₇(n)⌋ + 1
. Each iteration performs constant time operations (modulo, integer division, and appending to a list), so the overall time complexity is O(log₇(n))
. The final reversal operation ans[::-1]
takes O(log₇(n))
time as well, but this doesn't change the overall complexity.
Space Complexity: O(log₇(n))
where n
is the absolute value of the input number.
The space is primarily used by:
- The
ans
list which stores the digits of the base-7 representation. The maximum number of elements in this list is⌊log₇(n)⌋ + 1
. - The recursive call stack in the case of negative numbers adds at most one additional frame.
- The string created by
''.join(ans[::-1])
also takesO(log₇(n))
space.
Therefore, the overall space complexity is O(log₇(n))
.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Forgetting to Handle the Zero Case
One of the most common mistakes is not properly handling when num = 0
. Without the special case check, the while loop while num > 0
would never execute, resulting in an empty string being returned instead of '0'
.
Incorrect Implementation:
def convertToBase7(self, num: int) -> str:
if num < 0:
return '-' + self.convertToBase7(-num)
digits = []
while num > 0: # This loop never runs when num = 0
digits.append(str(num % 7))
num //= 7
return ''.join(reversed(digits)) # Returns '' for num = 0
Solution: Always include the zero check at the beginning of the function before any other logic.
2. Forgetting to Reverse the Digits
During the extraction process, digits are collected from least significant to most significant (right to left). A common error is forgetting to reverse them before joining.
Incorrect Implementation:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
if num < 0:
return '-' + self.convertToBase7(-num)
digits = []
while num > 0:
digits.append(str(num % 7))
num //= 7
return ''.join(digits) # Wrong! This gives reversed result
# For num = 100, this returns '202' instead of '202' (happens to be same)
# For num = 10, this returns '31' instead of '13'
Solution: Always reverse the collected digits using reversed(digits)
or digits[::-1]
before joining them.
3. Integer Overflow with Minimum Integer Value
In languages with fixed integer sizes (like Java or C++), handling Integer.MIN_VALUE
can cause overflow when negating it, since the positive equivalent doesn't fit in the integer range. While Python handles arbitrary precision integers, this is still worth noting for implementations in other languages.
Problematic Pattern in Other Languages:
// In Java, this could overflow if (num < 0) { return "-" + convertToBase7(-num); // -Integer.MIN_VALUE causes overflow }
Solution: For languages with fixed integer sizes, handle the conversion using unsigned operations or convert to a larger data type first. In Python, this isn't an issue due to arbitrary precision integers.
4. Using String Concatenation in Loop
While not incorrect, using string concatenation in the loop instead of collecting in a list can be inefficient.
Inefficient Implementation:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
if num < 0:
return '-' + self.convertToBase7(-num)
result = ''
while num > 0:
result = str(num % 7) + result # String concatenation is O(n) each time
num //= 7
return result
Solution: Use a list to collect digits and join them at the end for O(n) total time complexity instead of O(n²) from repeated string concatenation.
Which algorithm should you use to find a node that is close to the root of the tree?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!