Given an integer, return its base 7 string representation.
-2,147,483,648
to 2,147,483,647
.0
, return "0"
directly.7
and record the remainder.#include <iostream>
#include <string>
std::string convertToBase7(int num) {
if (num == 0) return "0";
bool isNegative = num < 0;
num = std::abs(num);
std::string result;
while (num > 0) {
result = std::to_string(num % 7) + result;
num /= 7;
}
if (isNegative) {
result = "-" + result;
}
return result;
}
int main() {
// Test cases
std::cout << convertToBase7(100) << std::endl; // Output "202"
std::cout << convertToBase7(-7) << std::endl; // Output "-10"
std::cout << convertToBase7(0) << std::endl; // Output "0"
std::cout << convertToBase7(49) << std::endl; // Output "100"
return 0;
}
O(log₇(n))
where n
is the input number. This is due to the fact that we are dividing the number by 7
repeatedly, thus the number of iterations will be proportional to the logarithm of the number in base 7
.O(log₇(n))
to store the resulting string.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?