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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容