Base 7 - Problem

Given an integer num, return a string of its base 7 representation.

Base 7 uses digits 0-6, where each position represents a power of 7. For example, the number 100 in base 10 equals 2*7² + 0*7¹ + 2*7⁰ = 202 in base 7.

Input & Output

Example 1 — Positive Number
$ Input: num = 100
Output: "202"
💡 Note: 100 ÷ 7 = 14 remainder 2, 14 ÷ 7 = 2 remainder 0, 2 ÷ 7 = 0 remainder 2. Reading remainders from bottom to top: "202"
Example 2 — Negative Number
$ Input: num = -7
Output: "-10"
💡 Note: Convert absolute value: 7 ÷ 7 = 1 remainder 0, 1 ÷ 7 = 0 remainder 1. Result is "10", add minus sign: "-10"
Example 3 — Zero
$ Input: num = 0
Output: "0"
💡 Note: Special case: 0 in any base is "0"

Constraints

  • -107 ≤ num ≤ 107

Visualization

Tap to expand
Base 7 Conversion - Recursive Approach INPUT num = 100 (decimal) Convert to Base 7 Powers of 7: 7^0 = 1 7^1 = 7 7^2 = 49 7^3 = 343 (ones) (sevens) (forty-nines) (too big!) Input: 100 ALGORITHM STEPS 1 Base Case Check If num < 7, return num 2 Recursive Call convert(num / 7) 3 Get Remainder num % 7 (current digit) 4 Combine Results Append digit to result Recursive Trace: convert(100) --> convert(14) + "2" --> convert(2) + "0" --> "2" (base) 100%7=2, 14%7=0, 2%7=2 FINAL RESULT Base 7 of 100: "202" Verification: 2 x 49 = 98 0 x 7 = 0 2 x 1 = 2 Total = 100 OK Output: "202" Key Insight: The recursive approach naturally builds the result from most significant to least significant digit. Each recursive call handles num/7 (higher digits), then appends num%7 (current digit). Base case: when num < 7, it's already a valid base-7 digit (0-6). Time: O(log7 n), Space: O(log7 n) TutorialsPoint - Base 7 | Recursive Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen