algoadvance

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

  1. Can the input number be negative?
    • Yes, the example indicates that the input number can be negative.
  2. 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.
  3. 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

  1. Handle special Case:
    • If the input num is zero, simply return the string “0”.
  2. Determine Sign:
    • Check if the number is negative. If so, keep track of the sign and work with the absolute value of the number.
  3. 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).
  4. Add Sign Back:
    • If the original number was negative, add a negative sign to the final base-7 string.
  5. 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

With this approach, we efficiently and correctly convert any integer within the given range to its base-7 representation.

Try our interview co-pilot at AlgoAdvance.com