【程序18】 题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时 共有5个数相加),几个数相加有键盘控制

来源:互联网 发布:阿里云vpn服务器 l2tp 编辑:程序博客网 时间:2024/05/21 07:51

方法一:


按照定义模拟,这个效率比常见的低,因为取余操作多。

#include <stdio.h>int main(){int n,t,res;while(~scanf("%d%d",&n,&t)){res = 0;while(t--){res += n;n = n*10 + n%10;}printf("%d\n",res);}return 0;}


方法二:


模拟一个简单功能的大数加:

#include <iostream>using namespace std;struct big{int *res;int *temp;big(int num,int len){res  = new int[len+1];for(int i=0;i<=len;res[i] =0,++i);temp = new int[len+1];for(int i=0;i<=len;temp[i]=0,++i);for(int i=0;i<len;++i){temp[i] = num;for(int j=0;j<=i;++j)res[j] += temp[j];}for(int i=0;i<len;++i){res[i+1] += res[i]/10;res[i] = res[i]%10;}if(res[len])len++;for(int i=len-1;i>=0;--i)printf("%d",res[i]); printf("\n");}~big(){delete[] res;delete[] temp;}};int main(){int num,len;while(~scanf("%d%d",&num,&len))big(num,len);return 0;}


原创粉丝点击