415. Add Strings

2018-07-14  本文已影响0人  bin_guo

Leetcode: 2. 415. Add Strings
Given two non-negative integers num1 and num2 represented as a 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.
Solution:
class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int num = 0;
        int str = 0;
        for(int p_1 = num1.length()-1, p_2 = num2.length()-1; p_1 >= 0 || p_2 >= 0; p_1--, p_2--) {
            if(p_1 >= 0 && p_2 >= 0)
                str = num1.charAt(p_1) - '0' + num2.charAt(p_2) - '0' + num;
            else
                str = (p_1 >= 0)?(num1.charAt(p_1) - '0' + num):(num2.charAt(p_2) - '0' + num);
            num = str / 10;
            str %= 10;
            sb.append(str);
        }
        if (num > 0)
            sb.append(num);
        return sb.reverse().toString();
    }
}
上一篇下一篇

猜你喜欢

热点阅读