Algorithm questions daily practice---Day 81: High-precision addition

Get into the habit of writing together! This is the 13th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the event details .

1. Problem description

Given two positive integers (without leading zeros), compute their sum.

in, 1 Integer length 100000 1≤integer length≤100000

Topic link: High-precision addition .

Second, the subject requirements

Example 1

输入: 12    23
输出: 35
复制代码

Example 2

输入: 123  98
输出: 221
复制代码

visit

1.高精度
2.建议用时15~30min
复制代码

3. Problem Analysis

The number of this question is obviously beyond the range of all shaping, we can use the string string storage, where the storage range of the string is: 1~65400个字符. After inputting through the string, we need to calculate the number, so the char->int type -'0'meets the .

We use an array to store each digit. Before the official start, we think about a question, is it stored in the forward direction or in the reverse direction?

For example, for the number 75842, which of the following storage methods should be used:

下标:0 1 2 3 4
数字:7 5 8 4 2

下标:4 3 2 1 0
数字:7 5 8 4 2
复制代码

Definitely use the second one! The first one, you can see if the highest position can move forward, and then it will be -1.

For the addition rule, use the corresponding bits learned in elementary school to add up, and add 1 to 10 when full.

Fourth, the encoding implementation

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
vector<int> add(vector<int> &a, vector<int> &b)  
{
    int i,k=0;//初始进位为0
    vector<int>c;
    for(i=0;i<a.size()||i<b.size();i++)//在范围内
    {
        if(i<a.size()) k+=a[i];
        if(i<b.size()) k+=b[i];
        c.push_back(k%10);//%10添加
        k=k/10;//进位
    }
    if(k)//确保遗留的进位添加进去
       c.push_back(k); 
    return c;
}
int main()
{
    string s1,s2;//字符串存储
    int i;
    cin>>s1>>s2;
    vector<int>a,b,c;
    for(i=s1.size()-1;i>=0;i--)//字符串转数字,倒序存储
        a.push_back(s1[i]-'0');
    for(i=s2.size()-1;i>=0;i--)//字符串转数字,倒序存储
        b.push_back(s2[i]-'0');
    c=add(a, b);//加法法则
    for (i=c.size()-1;i>=0;i--)//输出结果
        cout<<c[i];
    return 0;
}
复制代码

5. Test results

1.png

Guess you like

Origin juejin.im/post/7086996262028836871