1. 程式人生 > >leetcode (Add Strings)

leetcode (Add Strings)

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

}