[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();
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83656357
今日推荐