LeetCode(八)415. Add Strings

题目要求如下

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

Note:

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

两个数相加,考虑进位问题可以使用一个进位数来判断是否进位,处理字符串转换为char[]比较方便。

public class Solution {
    public String addStrings(String num1, String num2) {
       int i = num1.length() - 1;
        int j = num2.length() - 1;
        int carry = 0;
        char[] num1Array = num1.toCharArray();
        char[] num2Array = num2.toCharArray();
         StringBuilder sb = new StringBuilder();
        while (i >= 0 || j >= 0 || carry == 1) {
            int a = i >= 0 ? (num1Array[i--] - '0') : 0;
            int b = j >= 0 ? (num2Array[j--] - '0') : 0;
            int sum = a + b + carry;
            sb.insert(0, sum % 10);
            carry = sum / 10;
        }
        return sb.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/srping123/article/details/77371931
今日推荐