LeetCode(八)415. Add Strings

来源:互联网 发布:汽配软件 编辑:程序博客网 时间:2024/06/16 13:34

题目要求如下

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