百位数精确求和

来源:互联网 发布:在线对对联软件 编辑:程序博客网 时间:2024/06/13 00:18

FJNU.1743

Description
键入两个高精度非负整数(不超过230位),求它们的和(精确值)。

Input
数字串1
数字串2

Output
两数之和(并换行回车)

Sample Input
234567891234
143986543788123

Sample Output
144221111679357

My Program

#include<iostream>
#include
<string.h>
using namespace std;

int main()
{
    
int i,j,m,n,c;
    
char a[230],b[230];
    scanf(
"%s",a);
    scanf(
"%s",b);
    
if(a[0]=='0'&&b[0]=='0')
    
{
        cout
<<0<<endl;
        
return 0;
    }

    m
=strlen(a);
    n
=strlen(b);
    
if(m>n)
    
{
        c
=m-n;
        
for(i=n-1;i>=0;i--)
        
{
            j
=i+c;
            a[j]
+=b[i]-'0';
            
while(a[j]>'9')
            
{
                a[j]
-=10;
                a[
--j]++;
            }

        }

        
if(a[0]=='0'&&(m||n))
            cout
<<1;
        
for(i=0;i<m;i++)
            cout
<<a[i];
    }

    
else
    
{
        c
=n-m;
        
for(i=m-1;i>=0;i--)
        
{
            j
=i+c;
            b[j]
+=a[i]-'0';
            
while(b[j]>'9')
            
{
                b[j]
-=10;
                b[
--j]++;
            }

        }

        
if(b[0]=='0'&&(m||n))
            cout
<<1;
        
for(i=0;i<n;i++)
            cout
<<b[i];
    }

    cout
<<endl;
    
return 0;
}

YOYO's Note: 
高精度的加法。
用字符串按位从右开始算,同时判断是否进位,最后输出。

原创粉丝点击