Base 7 — Solution in Python, Java & C++
Base 7 solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on math, asked at Amazon and Adobe.
Base 7 is an easy coding problem on math, asked in Amazon and Adobe interviews.
- Difficulty: Easy
- Topics: Math
- Asked at: Amazon, Adobe
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an integer num, return its base-7 representation as a string.
Example 1
Input: num = 100
Output: 202
Example 2
Input: num = -7
Output: -10
Example 3
Input: num = 0
Output: 0
Constraints
-10000000 <= num <= 10000000
Hints for Base 7
Hint 1
Handle zero up front — the loop below would produce an empty string for it.
Hint 2
Take the absolute value, then repeatedly divide by 7, prepending each remainder.
Hint 3
Re-attach the minus sign at the end for negative inputs.
How to solve Base 7
Repeated division by 7 on the absolute value, prepending remainders, with the sign restored at the end.
Approach
- Return
"0"for zero. - Divide
|num|by 7 collecting remainders from least significant. - Prefix
-if negative.
Why it works
Positional notation in base b is obtained by repeated mod b / div b.
Complexity
- Time —
O(log₇ num) - Space —
O(log₇ num)
Pitfalls
- Handle zero separately or the loop produces an empty string.
Reference solution
Python
def convertToBase7(num: int) -> str:
if num == 0:
return "0"
negative = num < 0
v = abs(num)
out = ""
while v:
out = str(v % 7) + out
v //= 7
return "-" + out if negative else outJava
public static String convertToBase7(int num) {
if (num == 0) return "0";
boolean negative = num < 0;
long v = Math.abs((long) num);
StringBuilder out = new StringBuilder();
while (v > 0) {
out.insert(0, (char) ('0' + (int) (v % 7)));
v /= 7;
}
return negative ? "-" + out.toString() : out.toString();
}C++
string convertToBase7(int num) {
if (num == 0) return "0";
bool negative = num < 0;
long long v = num < 0 ? -(long long) num : (long long) num;
string out;
while (v > 0) {
out = string(1, (char) ('0' + (int) (v % 7))) + out;
v /= 7;
}
return negative ? "-" + out : out;
}JavaScript
var convertToBase7 = function(num) {
if (num === 0) return "0";
const negative = num < 0;
let v = Math.abs(num);
let out = "";
while (v > 0) {
out = String(v % 7) + out;
v = Math.floor(v / 7);
}
return negative ? "-" + out : out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.