Python solution (linear time, and constant space) without using int built-in method with explanation

  • 0
    # linear time, and constant space complexity
    def multiply(self, num1_string, num2_string):
        string_to_int = { letter:number for number,letter in enumerate("0123456789") }
        num1 = num2 = 0
        multiplier = 1
        for i in range(len(num1_string)):
            num1 += string_to_int[num1_string[len(num1_string)-1-i]] * multiplier
            multiplier *= 10
        multiplier = 1
        for i in range(len(num2_string)):
            num2 += string_to_int[num2_string[len(num2_string)-1-i]] * multiplier
            multiplier *= 10
        return str(num1 * num2)

    Explanation: Convert both input strings (num1_string, num2_string) to integers via a string_to_int dictionary mapper. Then just multiply the integer variables, and return the product in string format.

  • 0

    That is not allowed in this question.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.