LeetCode-415. Add Strings

问题:https://leetcode.com/problems/add-strings/?tab=Description
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.给定两个字符串形式的正整数num1和num2,计算num1和num2之和。
Note:
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.
在不用库的情况下实现加法。
分析:注意进位,注意处理长短不一样的数字,从末尾开始相加。如果两个字符长度都小于等于0,返回空字符串。某一个长度小于0,返回另一个字符串即可。对于数字和字符的相互转换,这里需要用到‘0’。字符转数字,减去’0’。数字转字符,加上’0’。
C++代码:

class Solution {
public:
    string addStrings(string num1, string num2) {
        int l1=num1.size();
        int l2=num2.size();
        if(l1<=0 && l2<=0){
            return " " ;
        }
        else if(l1<=0){
            return num2;
        }
        else if(l2<=0){
            return num1;
        }
        else{
            string res="";
            int m=min(l1,l2);
            int i=l1-1;
            int j=l2-1;
            int a=0;
            int sum=0;
            while(m>0){
                sum=a+(num1[i]-'0')+(num2[j]-'0');
                a=sum/10;
                res+=sum%10+'0';
                i--;
                j--; 
                m--;
            }
            while(i!=-1){
                sum=a+(num1[i]-'0');
                a=sum/10;
                res+=sum%10+'0';
                i--;
            }
            while(j!=-1){
                sum=a+(num2[j]-'0');
                a=sum/10;
                res+=sum%10+'0';
                j--;
            }
            if(i==-1 && j==-1 && a!=0){
                res+=a+'0';
            }
            reverse(res.begin(), res.end());
            return res;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值