刷题笔记:LeetCode-989(大数加法)

题目

该题为简单题,以下为原题连接。
https://leetcode-cn.com/problems/add-to-array-form-of-integer/

个人解析

此题其实就是高精度加法的变形。根据之前的学习,个人总结出以下两个大数的加法模板。

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int a,b;
	cin>>a>>b;
	vector<int> ans;
	int sum=0,carry=0;
	while(a||b||carry){
		sum=a%10+b%10+carry;
		ans.push_back(sum%10);
		carry=sum/10;
		a=a/10;
		b=b/10;
	}
	reverse(ans.begin(),ans.end());
	for(int i=0;i<ans.size();i++)
		cout<<ans[i];
	cout<<endl;
 } 

代码

class Solution {
public:
    vector<int> addToArrayForm(vector<int>& A, int K) {
        int len=A.size(),p=1,i=0,sum,carry=0;
        vector<int> ans;
        for(i=len-1;i>=0;i--){
            sum=A[i]+K%10+carry;
            ans.push_back(sum%10);
            carry=sum/10;
            K=K/10;
        }
        while(carry||K){
            sum=carry+K%10;
            ans.push_back(sum%10);
            carry=sum/10;
            K=K/10;
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

以上代码如有错误,请多多指正!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值