1:HDOJ1002
題目大意:給定兩個整數(整數位數都小於1000) 精算兩個數的和。並按要求格式輸出。
解體思路:使用char數據接收數據,並按位計算兩個數的和,保存在c數組中。
容易出現的問題:剛開始思路是有的,但是寫代碼的時候犯混了總以爲 char[0] 是個位,而char的最高位是整數的最高位,這樣寫完測試用例可以通過,
但是 當輸入 99999 和1 的時候就會輸出錯誤。 正確思路是:char數組的最後一位是個位,char[0] 是輸入整數的最高位。此外輸出格式也有特殊要求,每個case中間需要輸出一個額外的空行,而最後一個case則不需要,所以需要用一個if語句判斷一下。
代碼如下:
//Time:15MS
//Mem :364K
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
char a[1001];
char b[1001];
char c[1001];
int t;
cin>>t;
for(int i=1;i<=t;i++)
{
cin>>a>>b;
int rest = 0;
int len =0;
int lena = strlen(a)-1;
int lenb = strlen(b)-1;
for(;lena>=0||lenb>=0;lena--,lenb--)
{
if(lena>=0)
rest += a[lena]-'0';
if(lenb>=0)
rest += b[lenb]-'0';
c[len++] = rest%10 + '0';
rest = rest/10;
}
cout<<"Case "<<i<<":"<<endl;
cout<<a<<" + "<<b<<" = ";
if(rest != 0)
cout<<(char)(rest+'0');
c[len]='\0';
for(int j=len-1;j>=0;j--)
cout<<c[j];
cout<<endl;
if(i != t)
cout<<endl;
}
return 0;
}
2:HD1042
題目大意:給定一個數N(1=<N<=10000)計算N的階乘,跟POJ1001的思路是一樣的。
遇到的問題:數組至少得開闢4W大小要不就會WA掉,而且按照這種做法時間會在2.5S以上,在statistic版看到一個用gcc提交的只需要109MS.後來對我的代碼也做一下優化,但是還是找少得2S多。
代碼如下(待優化):
//Time:2073MS
//Mem :500K
#include <iostream>
#include <string.h>
using namespace std;
#define SIZE 30000
int main()
{
int n;
int ans[SIZE];
while(cin>>n)
{
memset(ans,0,sizeof(ans));
int temp = n;
int len = 0;
ans[0] =1;
int rest = 0;
for(int i=2;i<=n;i++)
{
for(int j=0;j<SIZE;j++)
{
ans[j] = ans[j]*i + rest;
rest = ans[j]/10;
ans[j] = ans[j]%10;
}
}
for(int i=SIZE-1;i>=0;i--)
if(ans[i]==0)
continue;
else
{
len = i;
break;
}
for(int i=len;i>=0;i--)
cout<<ans[i];
cout<<endl;
}
return 0;
}