求s=a+aa+aaa+aaaa+aa...a的值问题的C语言延伸代码图解(大数据也OK)

2017-12-26 10:25:09来源:http://www.dotcpp.com/blog/3970.html作者:极客头条人点击

分享

解题思路:


设n=5;则sum=a+aa+aaa+aaaa+aaaaa;



分析:


1.n个数相加,考虑到进位如99999+9999,需要长度为n+1的数组存放结果;


2.如图,个位结果为n- 0 个a的和,十位结果为n- 1 个a的和...万位为n- 4 个a的和;


for ( int i = n; i > 0; i-- )
sum[i] += i * a;

3.求出每位的和后,处理进位:从个位数开始,每一位先向前面一位进位,然后再求这一位对应数值(图中先蓝色,后绿色)


for ( int i = n; i > 0; i-- )
{
sum[i - 1]+= (sum[i] / 10);
sum[i]%= 10;
}

4.输出结果:如果sum[0]==0的话,最高位没有收到进位,输出sum[1]到sum[n],否则输出sum[0]到sum[n];


if ( sum[0] == 0 )
{
for ( int i = 1; i <= n; i++ )
printf( "%d", sum[i] );
}else
for ( int i = 0; i <= n; i++ )
printf( "%d", sum[i] );

注意事项:


开辟数组长度为n+1;最高位数下标为0,个位数下标为n;


参考代码: a为正


#include <stdio.h>
#include <malloc.h>
void format( int *sum, int n );
void function( int *sum, int a, int n );
/*===================================================*/
int main()
{
inta, n;
int*sum;
scanf( "%d%d", &a, &n );
sum = (int *) malloc( (n + 1) * sizeof(int) );
format( sum, n );
function( sum, a, n );
return(0);
}
/*===================================================*/
void format( int *sum, int n )
{
for ( int i = 0; i <= n; i++ )
sum[i] = 0;
}
/*===================================================*/
void function( int *sum, int a, int n )
{
for ( int i = n; i > 0; i-- )
sum[i] += i * a;
/*------------------------------------*/
for ( int i = n; i > 0; i-- )
{
sum[i - 1]+= (sum[i] / 10);
sum[i]%= 10;
}
/*------------------------------------*/
if ( sum[0] == 0 )
{
for ( int i = 1; i <= n; i++ )
printf( "%d", sum[i] );
}else
for ( int i = 0; i <= n; i++ )
printf( "%d", sum[i] );
return ;
}

等哪天上面代码不正确了:说明测试数据有a为负数,那么用下面代码正负a都对,a为负,会加负号;


#include <stdio.h>
#include <malloc.h>
#include <math.h>
void format( int *sum, int n );
void function( int *sum, int a, int n );
/*===================================================*/
int main()
{
inta, n;
int*sum;
scanf( "%d%d", &a, &n );
sum = (int *) malloc( (n + 1) * sizeof(int) );
format( sum, n );
function( sum, a, n );
return(0);
}
/*===================================================*/
void format( int *sum, int n )
{
for ( int i = 0; i <= n; i++ )
sum[i] = 0;
}
/*---------------------------------------------------*/
void function( int *sum, int a, int n )
{
for ( int i = n; i > 0; i-- )
sum[i] += i * fabs( a );
/*------------------------------------*/
for ( int i = n; i > 0; i-- )
{
sum[i - 1]+= (sum[i] / 10);
sum[i]%= 10;
}
/*------------------------------------*/
if ( sum[0] == 0 )
{
if ( a < 0 )
printf( "-" );
for ( int i = 1; i <= n; i++ )
printf( "%d", sum[i] );
}else{
if ( a < 0 )
printf( "-" );
for ( int i = 0; i <= n; i++ )
printf( "%d", sum[i] );
}
return;
}

别忘点赞哦-.-


最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台