HDOJ 1753

点击打开链接


解题思路:我们开两个数组,数组的前500位存储整数部分,后面500位存储小数部分,开个sum数组求和即可,注意一下小数点的进位


代码:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int s1[1000],s2[1000],sum[1000];
string str1,str2;
void copy()
{
   int i , j;
   int l1 = str1.size();
   int l2 = str2.size();
   int mark1 , mark2;
   memset(s1,0,sizeof(s1));
   memset(s2,0,sizeof(s2));
   for(i=0;i<l1;i++)
   {
       if(str1[i] == '.')
       {
           mark1 = i;
           break;
       }
   }
   if(i == l1)
       mark1 = l1;
   for(i=0;i<l2;i++)
   {
       if(str2[i] == '.')
       {
           mark2 = i;
           break;
       }
   }
   if(i == l2)
   {
       mark2 = l2;
   }
   
   
   for(i = mark1-1,j = 0;i >= 0;i--,j++)
   {
       s1[j] = str1[i]-48;
   }
   for(i = mark1+1,j = 501;i<l1;i++,j++)
   {
       s1[j] = str1[i]-48;
   }
    
   
   for(i = mark2-1,j = 0;i >= 0;i--,j++)
   {
       s2[j] = str2[i]-48;
   }
   for(i = mark2+1,j = 501;i<l2;i++,j++)
   {
       s2[j] = str2[i]-48;
   }  
}
void Plus()
{
    int i , j;
    int max;
    memset(sum,0,sizeof(sum));
    for(i=999;i>500;i--)
    {
        sum[i] += (s1[i] + s2[i]);
        if(sum[i] >= 10)
        {
            sum[i-1] +=sum [i]/10;
            sum[i] %= 10;
        }  
    }  
    s1[0]+=sum[500];
    for(i=0;i<=500;i++)
    {
        sum[i] += (s1[i] + s2[i]);
        if(sum[i] >= 10)
        {
            sum[i+1] += sum[i]/10;
            sum[i] %= 10;
        }  
    }
      
}
void output()
{
    int i , j;
    i = 500;
    while(i--)
    {
        if(sum[i] != 0)
            break;   
    }
    for(;i>=0;i--)
    {
        cout<<sum[i];
    }
    i = 999;
    while(i>500)
    {
        if(sum[i] != 0)
            break;
        i--;
    }
    if(i>500)
        cout<<".";
    for(j=501;j<=i;j++)
    {
        cout<<sum[j];
    }
    cout<<endl;   
}
int main()
{
    
    int i , j;
    while(cin>>str1>>str2)
    {
        copy();
        Plus();
        output();    
    }
    return 0;
}


上一篇:hdu 1800 Flying to the Mars


下一篇:HDOJ 1047