题目:
一个整数n的阶乘可以写成n!,它表示从1到n这n个整数的乘积。阶乘的增长速度非常快,例如,
13!就已经比较大了,已经无法存放在一个整型变量中;而35!就更大了,它已经无法存放在一个浮点型变量中。因此,当n比较大时,去计算n!是非常困难的。幸运的是,在本题中,我们的任务不是去计算n!,而是去计算n!最右边的那个非0的数字是多少。例如,5!=12345=120,因此5!最右边的那个非0的数字是2。再如,7!=5040,因此7!最右边的那个非0的数字是4。再如,15!= 1307674368000,因此15!最右边的那个非0的数字是8。请编写一个程序,输入一个整数n(0<n<=100)
然后输出n!最右边的那个非0的数字是多少。
输入:
7
输出:
4
- 分析思路:
单纯的算阶乘就比较简单了,而题目需要的却是结果最右边的非0数字,
while(a[i]%10==0){
a[i]=a[i]/10;
}
stringstream用法
当我们需要按预定的格式将程序中的数据保存在一个string 中的时候,可以先创建一个stringstream 对象,并通过运算符 ”<<“ 将数据传递给 stringstream 对象。(这与通过”<<“ 使用cout 对象的方法相同。)接着,我们可以通过调用stringstream 类的函数str() 将对象所包含的内容赋给一个string对象。在下面的程序中,我们先将数据传递给一个stringstream 对象,然后通过该 stringstream 对象将数值赋给一个string 对象。
stringstream sstr;
//--------int转string-----------
int a=100;
stringstream s;
string str;
s << n;
s >> str;
cout<<str<<endl;
//--------string转char[]--------
s.clear();//如果你想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数。
string name = "lina";
char cname[200];
s<<name;
s>>cname;
cout<<cname;
- 方法1代码:
#include <iostream>
#include <algorithm>
using namespace std;
int a[110];
void f()
{
a[0]=a[1]=1; //1!=1,0!=1
for(int i=2;i<=100;i++){
a[i]=i*a[i-1]; //阶乘核心算法
while(a[i]%10==0)
a[i]=a[i]/10;
a[i]%=10000;
}
}
int main()
{
int n;
f();
while(cin>>n){
cout<<a[n]%10<<endl; //保证输出最右边不为0的1位
}
return 0;
}
- 方法2代码:
#include<iostream>
#include<sstream>
using namespace std;
int f(int n)
{
stringstream s;
string str;
s << n;
s >> str;
if(str.size()<=2)
return n;
int i;
for(i =str.size()-1;i>=0;i--)
{
if(str[i]-'0'!=0)
break;
}
//cout << "str " << str << endl;
if(i==0)
str = str.substr(i,1);
else
str = str.substr(i-1,2);
s.clear();
s << str;
s >> n;
return n;
}
int main()
{
int n,a = 1;
cin >> n;
for(int i = 2;i <= n;i++)
{
a*=i;
a= f(a);
cout<< i << " a "<< a<< " a*(i+1)"<< a*(i+1) << endl;
}
while(a%10==0)
a/=10;
cout << a%10 << endl;
return 0;
}