Leetcode - Add Strings

My code:

public class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        while (i >= 0 || j >= 0) {
            if (i < 0) {
                int number = num2.charAt(j) - '0';
                int sum = number + carry;
                carry = sum / 10;
                sb.append(sum % 10);
                j--;
            }
            else if (j < 0) {
                int number = num1.charAt(i) - '0';
                int sum = number + carry;
                carry = sum / 10;
                sb.append(sum % 10);
                i--;
            }
            else {
                int number1 = num1.charAt(i) - '0';
                int number2 = num2.charAt(j) - '0';
                int sum = number1 + number2 + carry;
                carry = sum / 10;
                sb.append(sum % 10);
                i--;
                j--;
            }
        }
        
        if (carry != 0) {
            sb.append(carry);
        }
        
        return sb.reverse().toString();
    }
}

和 add list 差不多。

Anyway, Good luck, Richardo! — 10/12/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/a25c3efaad28
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞