算法:高精度

高進度加法

#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int main()
{
    char str1[100010],str2[100010];
    cin>>str1>>str2;
     
    int a1[100010],a2[100010],a[100010],n1,n2,i,k=0;
    
	n1=strlen(str1);
    n2=strlen(str2);
    for(i=0; i<n1/2; i++)
        swap(str1[i],str1[n1-1-i]);
    for(i=0; i<n2/2; i++)
        swap(str2[i],str2[n2-1-i]);
 
    for(i=0; i<n1; i++)
        a1[i]=str1[i]-'0';
    for(i=0; i<n2; i++)
        a2[i]=str2[i]-'0';
 
    if(n1>n2)
        swap(n1,n2);
    for(i=0; i<n2; i++)
        a[i]=a1[i]+a2[i];
 
    for(i=0; i<n2; i++)
    {
        if(a[i]>=10)
        {
            a[i]=a[i]%10;
            a[i+1]++;
        }
    }
    if(a[n2]!=0)
        cout<<a[n2];
    for(i=n2-1; i>=0; i--)
        cout<<a[i];
}

大數加法

#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cstring>
#include<cstdlib>
using namespace std;
const int maxn = 1024;
char str1[maxn], str2[maxn];
int  array_1[maxn], array_2[maxn];
void sum()
{
    for(int i = strlen(str1) - 1, j = 0; i >= 0; i--)
        array_1[j++] = str1[i] - '0';
    for(int i = strlen(str2) - 1, j = 0; i >= 0; i--)
        array_2[j++] = str2[i] - '0';
 
    for(int i = 0; i < maxn; i++)
    {
        array_2[i] += array_1[i];
        if(array_2[i] >= 10)
        {
            array_2[i + 1] += array_2[i] / 10;
            array_2[i] %= 10;
        }
    }
 
    int k=strlen(str1)>strlen(str2)?strlen(str1):strlen(str2) ;
    for( k=k ; k >= 0 && array_2[k] == 0; k--);
        if(k >= 0)
            for( ; k >= 0; k--)
                cout << array_2[k];
        else
            cout << 0;
    cout << endl;
}
 
int main()
{
    memset(array_1, 0, sizeof(array_1));
    memset(array_2, 0, sizeof(array_2));
    memset(str1, 0, sizeof(str1));
    memset(str2, 0, sizeof(str2));
    cin >> str1 ;
    cin >> str2 ;
    sum();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章