Sicily 1159. Sum

本文介绍了一种使用字符串模拟解决高精度算术问题的方法,通过实例代码展示了如何进行大数加法运算。该方法适用于超出常规整型变量所能表示的数值范围,通过逐位相加并进位的方式实现任意大小数字的加法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常见的高精度问题,用string模拟解决,根据个人习惯偏好,只要能过,怎样写都行。

Run Time: 0sec

Run Memory: 312KB

Code length: 879Bytes

SubmitTime: 2012-01-28 21:44:57

// Problem#: 1159
// Submission#: 1201505
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int N;
    int i, j;
    string r, s;
    int sum, carry;

    while ( cin >> N ) {
        r = string( 101, '0' );
        carry = 0;
        while ( N-- ) {
            cin >> s;   
            for ( i = s.size() - 1, j = 100; i >= 0; i--, j-- ) {
                sum = ( r[ j ] - '0' ) + ( s[ i ] - '0' ) + carry;
                carry = sum / 10;
                r[ j ] = sum % 10 + '0';
            }
            while ( carry != 0 ) {
                sum = ( r[ j ] - '0' ) + carry;
                carry = sum / 10;
                r[ j ] = sum % 10 + '0';
                j--;
            }
        }
        if ( r.find_first_not_of( '0' ) == string::npos )
            cout << 0 << endl;
        else
            cout << r.substr( r.find_first_not_of( '0' ) ) << endl;
    }

    return 0;

}                                 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值