Given an integer num
, return a string representing its base 7 representation.
Example 1:
Input: num = 100
Output: "202"
Example 2:
Input: num = -7
Output: "-10"
Constraints:
Clarifying Questions
- Can the input number be negative?
- Yes, the example indicates that the input number can be negative.
- Should the output always be in string format?
- Yes, the problem statement specifies that the output should be a string representing the base-7 number.
- Are there any special cases we need to handle, such as zero?
- Yes, if the input is zero, we should handle it specifically as its base-7 representation is also “0”.
Strategy
- Handle special Case:
- If the input
num
is zero, simply return the string “0”.
- Determine Sign:
- Check if the number is negative. If so, keep track of the sign and work with the absolute value of the number.
- Convert to Base 7:
- Continuously divide the number by 7 and keep track of the remainder.
- Append remainders to the result string, but build it in reverse order (from least significant digit to most significant digit).
- Add Sign Back:
- If the original number was negative, add a negative sign to the final base-7 string.
- Return the Result:
- Return the resulting base-7 string.
Code
def convertToBase7(num: int) -> str:
if num == 0:
return "0"
negative = num < 0
num = abs(num)
digits = []
while num > 0:
digits.append(str(num % 7))
num //= 7
if negative:
digits.append('-')
return ''.join(digits[::-1])
# Example Test Cases
print(convertToBase7(100)) # Output: "202"
print(convertToBase7(-7)) # Output: "-10"
print(convertToBase7(0)) # Output: "0"
Time Complexity
- The time complexity of this solution is O(log_7(n)) since we repeatedly divide the number by 7.
- The space complexity is also O(log_7(n)) due to storing the digits of the base-7 representation in a list.
With this approach, we efficiently and correctly convert any integer within the given range to its base-7 representation.
-
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?