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.
classSolution {
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();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funconvertToBase7(num: Int): String {
if (num ==0) return"0"var n = Math.abs(num)
val neg = num < 0val ans = StringBuilder()
while (n > 0) {
ans.append(n % 7)
n /=7 }
if (neg) ans.append('-')
return ans.reverse().toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defconvertToBase7(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 //=7return"-"+ ans if neg else ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnconvert_to_base7(num: i32) -> String {
if num ==0 {
return"0".to_string();
}
letmut n = num.abs();
letmut ans = String::new();
while n >0 {
ans.insert(0, char::from_digit((n %7) asu32, 10).unwrap());
n /=7;
}
if num <0 {
ans.insert(0, '-');
}
ans
}
}