浙江大学PAT上机题解析之2-06. 数列求和

时间:2022-09-14 17:08:26

给定某数字A(1<=A<=9)以及非负整数N(0<=N<=100000),求数列之和S = A + AA + AAA + … + AA…A(N个A)。例如A=1, N=3时,S = 1 + 11 + 111 = 123。

输入格式说明:

输入数字A与非负整数N。

输出格式说明:

输出其N项数列之和S的值。

样例输入与输出:

 

序号 输入 输出
1
1 3
123
2
6 100
7407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407340
3
1 0
0

第一种方法(未通过,最后一个case一直超时)

#include <iostream>
#include <string>
#include <algorithm>
using namespace std; inline string ADD(string a,string b)
{
string c;
string::reverse_iterator it1,it2 ;
int val,val1,val2;
int up=0;//进位
int i=0;
for (it1=a.rbegin(),it2=b.rbegin();it1!=a.rend()&&it2!=b.rend();it1++,it2++)
{
val1 = *it1-'0';
val2 = *it2-'0';
val = (val1+val2+up)%10;
c.push_back(val+'0');
up = (val1+val2+up)/10;
}
if (it1==a.rend())
{
while(it2!=b.rend())
{
val2 = *it2-'0';
val = (val2 +up)%10;
c.push_back(val+'0');
up = (val2+up)/10;
it2++;
}
}
if (it2==b.rend())
{
while(it1!=a.rend())
{
val1 = *it1-'0';
val = (val1 +up)%10;
c.push_back(val+'0');
up = (val1+up)/10;
it1++;
}
}
reverse(c.begin(),c.end());
return c;
} int main()
{ string Sn;
string temp;
int A,N;
cin>>A>>N;
if (N==0)
{
cout<<"0"<<endl;
}
else
{
int i;
for (i=1;i<=N;i++)
{
temp.push_back('0'+A);
Sn = ADD(Sn,temp);
} cout<<Sn<<endl; } //system("pause");
return 0;
}

第二种方法,已通过,是不是很简洁呢,嘿嘿

AAAA

   AAA

      AA

         A

请这么看求和,对应相加,是不是就是A*N+mod呢,mod为进位,N自减,请务必注意最后一次mod若不为零,则还要将mod加进去,附代码如下:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std; int main()
{ string temp;
int A,N;
cin>>A>>N;
if (N==0)
{
cout<<"0"<<endl;
}
else
{
int value=0;
int mod=0;
while(N)
{
value = (A*N+mod)%10;
temp.push_back('0'+value);
mod = (A*N+mod)/10;
N--;
}
if (mod!=0)
{
temp.push_back(mod);
}
reverse(temp.begin(),temp.end());
cout<<temp<<endl; } //system("pause");
return 0;
}