Given an integer num, return a string of its base 7 representation.
Example 1:
Input: num = 100
Output: "202"
Example 2:
Input: num = -7
Output: "-10"
Constraints:
- -107 <= num <= 107
My Solution
We first check if num is 0, which is a special case, for which we return “0”. We intialize a StringBuilder to construct our string. We first check if the number is negative because if it is we’ll need to append a ‘-’ to our StringBuilder at the end of processing our input. We also make the number positive by multiplying by -1. Then in our main loop we modulo with 7 at every iteration to get the digit and append that to our StringBuilder. We then divide the number by 7 at every iteration. The loop continues until num is 0, at which point we stop. Finally we our number was initially negative, we add a ‘-’. Finally we reverse our StringBuilder and return the underlying string.
Time complexity is O(log n) because we keep dividing the number by 7 at each iteration of our loop. Space complexity is also O(log n) due to the number of digits we require in our output string.
class Solution {
public String convertToBase7(int num) {
StringBuilder sb = new StringBuilder();
boolean neg = (num < 0);
if (num == 0) {
return "0";
}
if (num < 0) {
num *= -1;
}
while (num > 0) {
sb.append(num % 7);
num /= 7;
}
if (neg) {
sb.append('-');
}
return sb.reverse().toString();
}
}