leetcode (Add Strings)

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

Title:Add Strings    415

Difficulty:Easy

原题leetcode地址:   https://leetcode.com/problems/add-strings/

1.  进位补1,加1操作(从后到前)

时间复杂度:O(n),一次一层while循环,循环最长为n。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 进位补1,加1操作(从后到前)
     * @param num1
     * @param num2
     * @return
     */
    public static String addStrings(String num1, String num2) {

        if (num1.length() <= 0) {
            return num2;
        }
        if (num2.length() <= 0) {
            return num1;
        }

        int numIndex1 = num1.length() - 1;
        int numIndex2 = num2.length() - 1;
        int carry = 0;
        StringBuilder sb = new StringBuilder();

        while (numIndex1 >= 0 || numIndex2 >= 0) {
            int n1 = numIndex1 >= 0 ? num1.charAt(numIndex1) - '0' : 0;
            int n2 = numIndex2 >= 0 ? num2.charAt(numIndex2) - '0' : 0;
            int a = (n1 + n2 + carry) % 10;
            sb.insert(0, a + "");
            carry = (n1 + n2 + carry) / 10;
            numIndex1--;
            numIndex2--;
        }

        if (carry != 0) {
            sb.insert(0, carry + "");
        }

        return sb.toString();

}

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85346393
今日推荐