Leetcode#415. Add Strings (大数加法超简单写法)

题目

链接:https://leetcode.com/problems/add-strings/discuss/
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and 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.

题意

给你两个字符串,返回字符串的和。
注意:

  • 每个字符串的长度<5100。
  • 字符串中只包含数字0~9。
  • 字符串没有前导零。
  • 不能使用大数库和直接转换字符串。

思路

把字符串逐个存入int数组中。

简单写法
class Solution {
public:
    string addStrings(string num1, string num2) 
    {
        int i = num1.size()-1, j = num2.size()-1, carry = 0, sum = 0 , temp;
        string res="";
        while(i>=0 || j>=0 || carry>0)
        {
             temp = carry;
             if(i>=0)
                 temp += num1[i--]-'0';
             if(j>=0)
                 temp += num2[j--]-'0';
             carry = temp / 10; //进位
             res += to_string(temp % 10); //余数==本位
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

之前写过的基本解法:

基本写法

class Solution {
public:
    string addStrings(string num1, string num2) {
        int int_1[5101], int_2[5101], int_sum[5101], i, j, k=0, len=0, carry=0, temp=0, t=0;
        string res="";
        for(i=0;i<5101;i++)
        {  int_1[i]=0;
           int_2[i]=0;
           int_sum[i]=0;
        }
        len = 5101; 
        if(num1=="0"&&num2=="0")
            return "0";
        for(i=num1.size()-1; i>=0; i--)
            int_1[k++] = num1[i]-'0';
        for(i=num2.size()-1; i>=0; i--)
            int_2[t++] = num2[i]-'0';

        for(i=0; i<len; i++)
        {
            temp = int_1[i] + int_2[i] + carry;
            int_sum[i] = temp%10;
            carry = temp/10;
        }
        for(i=len-1;; i--)
        {
            if(int_sum[i]!=0)
            {
                t = i;
                break;
            }
        }
        for(j=t; j>=0; j--)
            res+=to_string(int_sum[j]);
        return res;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值