美文网首页
415. Add Strings

415. Add Strings

作者: bin_guo | 来源:发表于2018-07-14 15:13 被阅读0次

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

    相关文章

      网友评论

          本文标题:415. Add Strings

          本文链接:https://www.haomeiwen.com/subject/mbbdpftx.html