zoukankan      html  css  js  c++  java
  • 计算机考研复试真题 数字阶梯求和

    题目描述

    给定a和n,计算a+aa+aaa+a...a(n个a)的和。

    输入描述:

    测试数据有多组,输入a,n(1<=a<=9,1<=n<=100)。

    输出描述:

    对于每组输入,请输出结果。
    示例1

    输入

    1 10
    

    输出

    1234567900




    /*
    解题思路:数目较大,强行相加可能会溢出。这类题大概有两种思路:1.字符串拼接 2.将位数存在数组里或者用栈.
            具体思路:根据递推式,知道每位都是a,且个位数n个,十位数n-1个,以此类推...  
                    可先算个位,十位,...,先进个位最后输出个位,正好满足栈的思想,故分别将其入栈然后最后出栈。
    */
    #include<iostream>
    #include<stack>
    using namespace std;
    
    int main(){
        int a,n;
        while(cin>>a>>n){
            stack<int>ans;
            int temp=0;  //存放进位
            for(int i=n;i>0;--i){
                ans.push((i*a+temp)%10);  //依次求个位 十位 百位 ...
                temp=(i*a+temp)/10;  //保存进位
            }
            if(temp!=0)
                cout<<temp;  //输出最后的进位
            while(!ans.empty()){
                cout<<ans.top();
                ans.pop();
            }
            cout<<endl;
        }
        return 0;
    }
  • 相关阅读:
    Hibernate优缺点
    Struts优缺点
    Problem M
    Problem K
    Problem K
    Problem Q
    Problem Q
    Problem F
    Problem F
    哈夫曼树
  • 原文地址:https://www.cnblogs.com/parzulpan/p/9923051.html
Copyright © 2011-2022 走看看