poj 1503 Integer Inquiry【高精度】
這題總算是沒有那麼水的感覺了,不過還是水題,哈哈哈。。。題目主要是求高精度----大數的和,我專門寫了一個add函數處理,sum和VeryLongIntegers是兩個全局的變量,開始我還準備把sum也寫成char型的字符串,但是考慮到結尾的‘\0’,那不是自找麻煩。。果斷換成int型數組,這樣就容易處理多了。
在add函數中,我把VeryLongIntegers又反轉了一次(即變成低位在前),也換成一個int型的數組,這樣就變成兩個int型數組的高精度加法了。。。
開始還覺得可能會WA一次,不過運氣是十分之好,一次AC,再接再厲咯。。。
忘說一句,題目的數據可能會有些變態,以0開頭。。。如果判斷VeryLongIntegers【0】==‘0’,就悲劇了
我的AC代碼
#include <stdio.h>
#include <string.h>
//變態的題目允許以0開頭
char VeryLongIntegers[105];
int sum[105]; //直接用int來放加後的結果,沒必要再用char型增加難度
//反轉之後的VeryLongIntegers和sum都是從低位到高位存放,==打印時要注意
void add()
{
int i;
//反轉VeryLongIntegers
int vers[105]={0};
int j=0;
for(i=strlen(VeryLongIntegers)-1;i>=0;i--)
{
vers[j]=VeryLongIntegers[i]-'0';
j++;
//printf("%d",vers[j-1]); //反轉OK
}
//這就變成了兩個int數組的大數加法了
int temp;
for(i=0;i<strlen(VeryLongIntegers);i++)
{
temp=vers[i]+sum[i];
if(temp>=10)
{
sum[i]=temp-10;
sum[i+1]++;
}
else
sum[i]=temp;
}
}
int main()
{
int i=0;
while(scanf("%s",VeryLongIntegers))
{
if(strcmp(VeryLongIntegers,"0")==0)
break;
add();
i++;
}
//如果前麵都是0,就繼續往前數
int j=103;
while(sum[j]==0)
{
j--;
}
for(i=j;i>=0;i--)
printf("%d",sum[i]);
printf("\n");
return 0;
}
後來又看了別人的結題報告 ,用STL真的很爽,string已經寫成一個類了,很多函數直接調用
別人的代碼
#include <iostream>
#include <string>
using namespace std;
#define SIZE 105
string s;
int sum[SIZE]={0};
int main()
{
int i,j;
while(cin>>s&&s.compare("0"))
{
for(j=SIZE-1,i=s.size()-1;i>=0;--i)
sum[j--]+=(s[i]-'0');
}
j=0;//處理時去除前麵的零
while(!sum[j])
++j;
if(j>=SIZE)
printf("0");
for(i=SIZE-1;i>=j;i--)//處理進位
{
sum[i-1]+=sum[i]/10;
sum[i]=sum[i]%10;
}
i=0;//輸出前去除前麵的零
while(!sum[i])
++i;
for(;i<SIZE;i++)
cout<<sum[i];
cout<<endl;
}
最後更新:2017-04-03 14:53:41