【LeetCode】415. Add Strings 字符串/大整數相加 - Easy

[LeetCode] 415. Add Strings 字符串相加

 

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

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

這道題讓我們求兩個字符串的相加,之前 LeetCode 出過幾道類似的題目,比如二進制數相加,還有鏈表相加,或是字符串加1,基本思路很類似,都是一位一位相加,然後算和算進位,最後根據進位情況看需不需要補一個高位,難度不大,參見代碼如下:

Java:

public class Solution {
    /**
     * @param num1: a non-negative integers
     * @param num2: a non-negative integers
     * @return: return sum of num1 and num2
     */
    public String addStrings(String num1, String num2) {
        // write your code here
         if(num1 == null || num1.length() == 0){
            return num2;
        }
        if(num2 == null || num2.length() == 0){
            return num1;
        }
        StringBuilder sb = new StringBuilder();
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        int carry = 0;  // 進位

        while(i >= 0 || j >= 0){
            int digit1 = i < 0? 0 : num1.charAt(i) - '0';
            int digit2 = j < 0? 0 : num2.charAt(j) - '0';
            sb.append((digit1 + digit2 + carry) % 10);
            carry = (digit1 + digit2 + carry) / 10; // 兩兩相加,溢出補0

            i--;
            j--;
        }
        if(carry == 1){
            sb.append('1');
        }

        return sb.reverse().toString();
    }
}

Python:

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        res = ""
        m = len(num1)
        n = len(num2)
        i = m - 1
        j = n - 1
        flag = 0
        while i >=0 or j >= 0:
            a = int(num1[i]) if i >=0 else 0
            i = i - 1
            b = int(num2[j]) if j >=0 else 0
            j = j - 1
            sum = a + b + flag
            res = str(sum % 10 ) + res;
            flag = sum / 10
        return res if flag == 0 else (str(flag)+ res)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章