一、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);
}