一、a+b
1、題目和要求
時間限制:1s,內存限制:32MB,特殊判題:否
2、總結
1)“1.6 貪心算法(含:c++限制數字位數)” 這篇文章介紹了<iomanip>
頭文件用於限制數字位數,函數爲setprecision(位數)
,這次又用到了限制字符寬度和佔位符,函數分別是setw(寬度)、setfill('填充字符')
。
cout<<setfill('0')<<setw(4)<<b.digit[i];
2)printf("%04d",digit[i]);
表示0爲佔位符,輸出長度爲4。
3)這道題需要注意的:
- 運算順序:何時應從後往前,何時應從前往後?
- 進位位的設置。
3、思路
由於算術運算都是從最後一位開始,諸位向前計算,因此保存在BigInteger
時,也應從後往前,每四位(位數隨意)按一個數字存放。所以不能採用下面的方法了:
scanf("%4d",&bigInteger[1].digit[bigInteger[1].size++]);
涉及到與BigInteger.digit[]
數組有關的運算:將字符串轉化爲數字、按正常顯示方式輸出BigInteger.digit[]
中的內容,都應從後往前開始。而進行加法運算時,由於最後四位存在了[0]
位,所以應從前往後進行。
4、代碼
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//每個數長度不超過1000位,1000/4=250
#define N 250
struct BigInteger{
int size;
int digit[N];
BigInteger(){
size = 0;
}
}bigInteger[2],sum;
void str2bigInteger(string str, BigInteger &b){
int num = 0;
int i = str.size()-1;
for( ; i>=0; i=i-4){
if(i<4){
for(int j=0; j<=i; j++){
num = num*10 + (str[j]-'0');
}
b.digit[b.size++] = num;
}else{
num = (str[i]-'0') + (str[i-1]-'0')*10 + (str[i-2]-'0')*100 + (str[i-3]-'0')*1000;
b.digit[b.size++] = num;
}
num = 0;
}
}
void printBigInteger(BigInteger b){
for(int i = b.size-1; i>=0; i--){
if(i == b.size-1){
cout<<b.digit[i];
}else{
cout<<setfill('0')<<setw(4)<<b.digit[i];
}
}
cout<<endl;
}
int main(){
string str1,str2;
cin>>str1>>str2;
str2bigInteger(str1,bigInteger[1]);
str2bigInteger(str2,bigInteger[2]);
//printBigInteger(bigInteger[1]);
//printBigInteger(bigInteger[2]);
//開始計算
int carry = 0;//進位標誌位
int i,j;//循環計數器
for(i=0,j=0 ;i<bigInteger[1].size && j<bigInteger[2].size; i++,j++){
int s = bigInteger[1].digit[i] + bigInteger[2].digit[j] + carry;
carry = s/10000;
sum.digit[sum.size++] = s%10000;
}
while(i<bigInteger[1].size){
int s = bigInteger[1].digit[i++] + carry;
carry = s/10000;
sum.digit[sum.size++] = s%10000;
}
while(j<bigInteger[2].size){
int s = bigInteger[2].digit[j++] + carry;
carry = s/10000;
sum.digit[sum.size++] = s%10000;
}
printBigInteger(sum);
}
二、N的階乘
1、題目和要求
時間限制:3s,內存限制:128MB,特殊判題:否
2、總結
搞清楚上一道題的運算順序和進位位後,這道題唯一的難點就在何時增加一位上。
if(carry != 0 && j == result.size){
result.digit[result.size++] = carry;
carry = 0;
}
3、代碼
#include <iostream>
#include <iomanip>
using namespace std;
#define N 250
struct BigInteger{
int size;
int digit[N];
BigInteger(){
size = 0;
}
}result;
void printBigInteger(BigInteger b){
for(int i = b.size-1; i>=0; i--){
if(i == b.size-1){
cout<<b.digit[i];
}else{
cout<<setfill('0')<<setw(4)<<b.digit[i];
}
}
cout<<endl;
}
int main(){
int n,carry = 0,i,j;
cin>>n;
result.digit[result.size++] = n;
for(i = n-1; i>0; i--){
for(j = 0; j<result.size; j++){
int mul = result.digit[j] * i + carry;
carry = mul/10000;
result.digit[j] = mul%10000;
}
if(carry != 0 && j == result.size){
result.digit[result.size++] = carry;
carry = 0;
}
}
printBigInteger(result);
}