解题思路:
设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() { int a, 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() { int a, 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; }
别忘点赞哦-.-
0.0分
17 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复