LintCode - Big Integer Addition(容易)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

注意事项:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

样例:
Given num1 = "123", num2 = "45"
return "168"
实现:
public class Solution {
    /*
     * @param num1: a non-negative integers
     * @param num2: a non-negative integers
     * @return: return sum of num1 and num2
     */
    public String addStrings(String num1, String num2) {
        if(num1 == null || num1.length() == 0){
            return num2;
        }
        if(num2 == null || num2.length() == 0){
            return num1;
        }
        
        StringBuilder ret = new StringBuilder();

        //位置
        int pos1 = num1.length() - 1;
        int pos2 = num2.length() - 1;

        //进位
        int c = 0;

        while (pos1 >= 0 || pos2 >= 0 || c != 0) {
            int i1 = 0;
            if (pos1 >= 0) {
                i1 = Integer.parseInt(num1.charAt(pos1--) + "");
            }
            int i2 = 0;
            if (pos2 >= 0) {
                i2 = Integer.parseInt(num2.charAt(pos2--) + "");
            }
            int result = c + i1 + i2;
            if (result >= 10) {
                ret.append(result % 10);
                c = result / 10;
            } else {
                ret.append(result);
                c = 0;
            }
        }

        return ret.reverse().toString();
    }
}

你可能感兴趣的:(LintCode - Big Integer Addition(容易))