504. Base 7
1. Description
Given an integer, return its base 7 string representation.
2. Example
Example 1:
Input: 100
Output: “202”
Example 2:
Input: -7
Output: “-10”
3. Note
- The input will be in range of [-1e7, 1e7].
4. Solutions
My Accepted Solution
n = number
Time complexity: O($log_7n$)
Space complexity: O(1)
class Solution
{
public:
// string convertToBase7(int num)
string convertToBase7(int number)
{
if(number == 0) return string("0");
string result(number >= 0 ? "" : "-");
number = abs(number);
// pow function will return a double, so it will have some loss of significance
int maxPower = 0;
while((int)round(pow(7, maxPower)) <= number) maxPower++;
maxPower--;
for(int digit; maxPower >= 0; maxPower--)
{
digit = number / (int)round(pow(7, maxPower));
number %= (int)round(pow(7, maxPower));
result.push_back(digit + '0');
}
return result;
}
};