Big Integer Addition存储在字符串内的整数相加

27 篇文章 0 订阅

题目:

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

 注意事项
  • 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.

思路:

char array与string类型的转换,特殊边界的处理

class Solution {
public:
    /*
     * @param num1: a non-negative integers
     * @param num2: a non-negative integers
     * @return: return sum of num1 and num2
     */
    string addStrings(string &num1, string &num2) {
        // write your code here
        int len1 = num1.size();
        int len2 = num2.size();
        string fres;
        if (len1 < len2) {
            int tmp = len1;
            len1 = len2;
            len2 = tmp;
            string tmpstr = num1;
            num1 = num2;
            num2 = tmpstr;
        }
        char res[len1+1];
        int index2 = len2-1;
        res[len1-1] = 0;
        for (int i = len1-1; i > 0; i--) {
            if (i > len1-len2-1) {
                if ( res[i]+num1[i] + num2[index2] -'0'-'0' >=10) {
                    res[i] += num1[i]+num2[index2]-'0'-10;
                    res[i-1] = 1;
                } else {
                    res[i] += num1[i]+num2[index2]-'0';
                    res[i-1] = 0; 
                }
                index2 -= 1;
            } else {
                if ( res[i]+num1[i] -'0' >=10) {
                    res[i] += num1[i]-10;
                    res[i-1] = 1;
                } else {
                    res[i] += num1[i];
                    res[i-1] = 0;
                }
            }
        }
        if (len1 == len2) {
            if ( res[0]+num1[0]+num2[0] -'0' -'0' >= 10) {
                res[0] += num1[0]+num2[0]-'0'-10;
                char res2[len1+2];
                for (int i = 0; i < len1; i++) {
                    res2[i+1] = res[i];
                }
                res2[0] = '1';
                fres.assign(res2, len1+1);
            } else {
                res[0] += num1[0]+num2[0]-'0';
                fres.assign(res, len1);
            }
        } else {
        if ( res[0]+num1[0] -'0' >= 10) {
            res[0] += num1[0]-10;
            char res2[len1+2];
            for (int i = 0; i < len1; i++) {
                res2[i+1] = res[i];
            }
            res2[0] = '1';
            fres.assign(res2, len1+1);
        } else {
            res[0] += num1[0];
            fres.assign(res, len1);
        }
        }
        return fres;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值