Base 7
Problem
Given an integer num, return its base-7 representation as a string.
num = 100"202"def convert_to_base7(num):
if num == 0:
return "0"
sign = "-" if num < 0 else ""
n, digits = abs(num), []
while n:
digits.append(str(n % 7))
n //= 7
return sign + "".join(reversed(digits))
function convertToBase7(num) {
if (num === 0) return "0";
const sign = num < 0 ? "-" : "";
let n = Math.abs(num);
const digits = [];
while (n) {
digits.push(n % 7);
n = Math.floor(n / 7);
}
return sign + digits.reverse().join("");
}
class Solution {
public String convertToBase7(int num) {
if (num == 0) return "0";
StringBuilder sb = new StringBuilder();
boolean neg = num < 0;
int n = Math.abs(num);
while (n > 0) {
sb.append(n % 7);
n /= 7;
}
if (neg) sb.append('-');
return sb.reverse().toString();
}
}
string convertToBase7(int num) {
if (num == 0) return "0";
bool neg = num < 0;
int n = abs(num);
string s;
while (n > 0) {
s += char('0' + n % 7);
n /= 7;
}
if (neg) s += '-';
reverse(s.begin(), s.end());
return s;
}
Explanation
Converting a number to base 7 uses the same trick as any base change: repeatedly divide by 7 and keep the remainders. Each remainder is one digit of the answer, and they come out from least significant to most significant.
We first handle two edge cases: 0 maps straight to "0", and a negative number is stored as a positive value while we remember a - sign to prepend later.
Then we loop while n is nonzero. Each pass takes n % 7 as the next digit and shrinks n with n //= 7. Since digits arrive in reverse order, we reverse them at the end and glue the sign back on.
Example: num = 100. 100 % 7 = 2, leaving 14; 14 % 7 = 0, leaving 2; 2 % 7 = 2, leaving 0. Digits collected are [2, 0, 2]; reversed they read "202", which checks out since 2·49 + 0·7 + 2 = 100.