蓝桥杯 ADV-121 算法提高 高精度加法

栏目: 编程工具 · 发布时间: 6年前

内容简介:问题描述输入格式两行,每行一个整数,每个整数不超过1000位

问题描述

在C/C++语言中,整型所能表示的范围一般为-231到231(大约21亿),即使long long型,一般也只能表示到-263到263。要想计算更加规模的数,就要用软件来扩展了,比如用数组或字符串来模拟更多规模的数及共运算。

输入格式

两行,每行一个整数,每个整数不超过1000位

输出格式

一行,两个整数的和。

样例输入

15464315464465465

样例输出

15464797786119616

数据规模和约定

每个整数不超过1000位

分析:1.模拟竖式加法,依次从往左加

2.如果刚开始两位数字位数不一样,短的用0补上,最后一次加法,如果有进位也要加上~

#include <iostream>
#include <string>
using namespace std;
string add(string s1, string s2) {
    int len1 = s1.length(), len2 = s2.length();
    if (len1 < len2) {
        string t(len2 - len1, '0');
        s1 = t + s1;
    } else if (len2 < len1) {
        string t(len1 - len2, '0');
        s2 = t + s2;
    }
    string ans = s1;
    int car = 0;
    for (int i = s1.length() - 1; i >= 0; i--) {
        ans[i] = (s1[i] - '0' + s2[i] - '0' + car) % 10 + '0';
        car = (s1[i] - '0' + s2[i] - '0' + car) / 10;
    }
    if (car) ans = (char) (car + '0') + ans;
    return ans;
}
int main() {
    string s1, s2;
    cin >> s1 >> s2;
    cout << add(s1, s2);
    return 0;
}
❤❤点击这里 -> 订阅PAT、蓝桥杯、GPLT天梯赛、LeetCode题解离线版❤❤ 蓝桥杯 ADV-121 算法提高 高精度加法

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Smashing Book

The Smashing Book

Jacob Gube、Dmitry Fadeev、Chris Spooner、Darius A Monsef IV、Alessandro Cattaneo、Steven Snell、David Leggett、Andrew Maier、Kayla Knight、Yves Peters、René Schmidt、Smashing Magazine editorial team、Vitaly Friedman、Sven Lennartz / 2009 / $ 29.90 / € 23.90

The Smashing Book is a printed book about best practices in modern Web design. The book shares technical tips and best practices on coding, usability and optimization and explores how to create succes......一起来看看 《The Smashing Book》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具