We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Base 7

Number: 504

Difficulty: Easy

Paid? No

Companies: Google, Amazon


Problem Description

Given an integer num, convert it to its base 7 string representation. The function should correctly handle negative numbers, where the minus sign is preserved.


Key Insights

  • Handle the edge case where num is 0.
  • Use division and modulo operations to extract base 7 digits.
  • Manage negative numbers by converting to positive and reattaching the minus sign.
  • Build the base 7 digits in reverse order during iteration.

Space and Time Complexity

Time Complexity: O(log_7(n)) where n is the absolute value of the number. Space Complexity: O(log_7(n)) to store the digits of the number.


Solution

The algorithm follows these steps:

  1. Check if num equals 0 and return "0".
  2. Determine if the number is negative. If so, work with its absolute value but remember the negative flag.
  3. Iteratively compute the remainder when divided by 7 (using modulo) and update the number by integer division by 7.
  4. Append each remainder (converted to character) to a list representing the digits.
  5. The digits are computed in reverse order; reverse the list for the correct order.
  6. If the original number was negative, append the "-" sign to the front.
  7. Join the digits to form the resulting base 7 string.

This approach uses basic arithmetic (division and modulo) and a list (or equivalent structure) to accumulate the computed digits.


Code Solutions

# Python solution for converting an integer to its base 7 string representation.
def convertToBase7(num):
    # Special case: If num is 0, return "0"
    if num == 0:
        return "0"
  
    # Flag to check if the number is negative
    negative = num < 0
    # Work with the absolute value of the number
    num = abs(num)
  
    # List to store base 7 digits
    digits = []
  
    # Process the number until it becomes 0
    while num > 0:
        # Get the remainder (digit in base 7) 
        remainder = num % 7
        # Append the digit as string to the list
        digits.append(str(remainder))
        # Update num by integer division by 7
        num //= 7
  
    # Reverse the list to get digits in correct order
    base7 = ''.join(reversed(digits))
    # If original number was negative, attach the minus sign
    return "-" + base7 if negative else base7

# Example usage:
print(convertToBase7(100))  # Expected output: "202"
print(convertToBase7(-7))   # Expected output: "-10"
← Back to All Questions