1. 程式人生 > >[LeetCode] 415. Add Strings(字串 加法)

[LeetCode] 415. Add Strings(字串 加法)

題:https://leetcode.com/problems/add-strings/description/

題目

Given two non-negative integers 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.Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.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.You must not use any built-in BigInteger library or convert the inputs to integer directly.

題目大意

十進位制的字串 加法。

思路

設定 兩指標 i,j 指向 字串num1、num2的尾部。設定 count 為本位的進位(該值由上位計算出)。

若 指標 i 大於等於0,count += num1[i] - ‘0’;
若 指標 j 大於等於0,count += num2[j] - ‘0’;

res += count%10,計算結果中 本位的值
count = count/10,計算下一位的進位。

class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder res =
new StringBuilder(); int cnt = 0; int i = num1.length()-1,j = num2.length()-1; while(i>=0 || j>=0 || cnt>0){ if(i>=0) cnt +=num1.charAt(i--) - '0'; if(j>=0) cnt +=num2.charAt(j--) - '0'; res.append(cnt%10); cnt = cnt/10; } return res.reverse().toString(); } }