自学内容网 自学内容网

Leetcode 415. Add Strings

Problem

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Algorithm

Simulate calculation using arrays.

Code

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        i, j = len(num1) - 1, len(num2) - 1 
        remainder = 0 
        result = "" 
        while i >= 0 or j >= 0 or remainder:
            n1 = ord(num1[i]) - ord('0') if i >= 0 else 0
            n2 = ord(num2[j]) - ord('0') if j >= 0 else 0
            bits = n1 + n2 + remainder
            remainder = bits // 10
            result = str(bits % 10) + result
            
            i -= 1
            j -= 1

        return result

原文地址:https://blog.csdn.net/mobius_strip/article/details/142892017

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!