Base 7
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer num, return a string of its base 7 representation.
Examples
Example 1
Input: num = 100
Output: "202"
Example 2
Input: num = -7
Output: "-10"
Constraints
-10^7 <= num <= 10^7
Solution
Method 1 – Repeated Division (Base Conversion)
Intuition
To convert a decimal number to base 7, repeatedly divide the number by 7 and collect the remainders. The remainders, read in reverse order, form the base 7 representation. Handle negative numbers by converting the absolute value and adding a minus sign if needed.
Approach
- If
numis 0, return"0". - Record if
numis negative; work with its absolute value. - While
numis greater than 0:
- Divide
numby 7, store the remainder. - Update
numto the quotient. - Append the remainder to a result list or string.
- Reverse the collected digits.
- Add a minus sign if the original number was negative.
- Return the result as a string.
Code
C++
class Solution {
public:
string convertToBase7(int num) {
if (num == 0) return "0";
bool neg = num < 0;
num = abs(num);
string ans;
while (num > 0) {
ans += to_string(num % 7);
num /= 7;
}
if (neg) ans += '-';
reverse(ans.begin(), ans.end());
return ans;
}
};
Go
func convertToBase7(num int) string {
if num == 0 {
return "0"
}
neg := num < 0
if neg {
num = -num
}
ans := ""
for num > 0 {
ans = string('0'+num%7) + ans
num /= 7
}
if neg {
ans = "-" + ans
}
return ans
}
Java
class Solution {
public String convertToBase7(int num) {
if (num == 0) return "0";
boolean neg = num < 0;
num = Math.abs(num);
StringBuilder ans = new StringBuilder();
while (num > 0) {
ans.append(num % 7);
num /= 7;
}
if (neg) ans.append('-');
return ans.reverse().toString();
}
}
Kotlin
class Solution {
fun convertToBase7(num: Int): String {
if (num == 0) return "0"
var n = Math.abs(num)
val neg = num < 0
val ans = StringBuilder()
while (n > 0) {
ans.append(n % 7)
n /= 7
}
if (neg) ans.append('-')
return ans.reverse().toString()
}
}
Python
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return "0"
neg = num < 0
n = abs(num)
ans = ""
while n > 0:
ans = str(n % 7) + ans
n //= 7
return "-" + ans if neg else ans
Rust
impl Solution {
pub fn convert_to_base7(num: i32) -> String {
if num == 0 {
return "0".to_string();
}
let mut n = num.abs();
let mut ans = String::new();
while n > 0 {
ans.insert(0, char::from_digit((n % 7) as u32, 10).unwrap());
n /= 7;
}
if num < 0 {
ans.insert(0, '-');
}
ans
}
}
Complexity
- ⏰ Time complexity:
O(log₇|num|)— Each division reduces the number by a factor of 7. - 🧺 Space complexity:
O(log₇|num|)— For storing the digits of the result.