LeetCode笔记:415. Add Strings

来源:互联网 发布:机甲风暴java 编辑:程序博客网 时间:2024/05/18 01:51

问题:

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.

大意:

给出两个字符串形式的非负数num1和num2,返回num1和num2之和。

注意:

1、num1和num2的长度都小于5100。
2、num1和num2都只包含数字0-9。
3、num1和num2都不包含处于首位的0。
4、你不能使用任何内置的大数库或者直接将输入转化成整型。

思路:

题目不允许直接转化成整型去计算,也就是要我们一位一位地将数字加起来实现一次加法了。从两个字符串的最末尾开始去加,注意判断是否要进位,一位位加到两个字符串都遍历完为止,为了速度这里要使用StringBuilder,如果直接用 + 去进行字符拼接就太慢了,注意我们每次对每位数进行加时还是用整型来计算,这还是允许的,不然也太麻烦了,代码比较容易看懂。

代码(Java):

public class Solution {    public String addStrings(String num1, String num2) {        if (num1.length() == 0) return num2;        else if (num2.length() == 0) return num1;        boolean hasUp = false;// 是否进位        int i = num1.length() - 1;        int j = num2.length() - 1;        StringBuilder sb = new StringBuilder();        while (i >=0 || j >= 0) {            int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;            int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;            int sum = n1 + n2 + (hasUp ? 1 : 0);            if (sum >= 10) {                sb.insert(0, Integer.toString(sum - 10));                hasUp = true;            } else {                sb.insert(0, Integer.toString(sum));                hasUp = false;            }            i--;            j--;        }        if (hasUp) sb.insert(0, "1");        return sb.toString();    }}

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

0 0
原创粉丝点击