LeetCode-Add Strings

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82936141

Description:
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.

题意:给定两个用字符串表示的非负整数,要求计算两个字符串整数的和,并以字符串的形式返回;并且,不能够使用内置的函数来直接转化;

解法:在这里,我们对字符串从低位到高位进行求和,并且记录其进位,直到遍历完两个字符串的所有位;

Java
class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder result = new StringBuilder();
        int index1 = num1.length() - 1;
        int index2 = num2.length() - 1;
        int carry = 0;
        while (index1 >= 0 || index2 >= 0) {
            int x1 = index1 >= 0 ? num1.charAt(index1) - '0' : 0;
            int x2 = index2 >= 0 ? num2.charAt(index2) - '0' : 0;
            int add = (x1 + x2 + carry) % 10;
            result.insert(0, "" + add);
            carry = (x1 + x2 + carry) / 10;
            index1--;
            index2--;
        }
        if (carry != 0) result.insert(0, "" + carry);
        return result.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82936141