九度机试笔记20170906


题目1051:数字阶梯求和

#include <stdio.h>

char res[105];
int main()
{
    int a, n;
    while(scanf("%d %d",&a,&n)!=EOF)
    {
        int sum=0;
        res[n+1]='\0';
        for(int i=n;i>=0;i--)
        {
            sum += a*i;
            res[i]=(sum%10)+'0';
            sum/=10;
        }
        if(res[0]=='0')
            printf("%s\n",&res[1]);
        else
            printf("%s\n",res);
    }
    return 0;
}

注意:开始我用的while(cin>>a>>n),虽然结果正确,但是提交上去通不过,不知道是不是不能同时使用cin和printf这两种输入输出函数。


题目1019:简单计算器

#include <iostream>
#include <stack>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main()
{
    char str[201],num[201];
    stack<double> S;
    while(cin.getline(str,201))
    {
        int len = strlen(str);
        if((len==1)&&str[0]=='0')
            return 0;
        int count = 0;
        double res;
        char op_pre = '\0';
        for(int i=0; i<=len; i++)
        {
            if(str[i]==' ') continue;
            if((str[i]>='0')&&(str[i]<='9'))
                num[count++]=str[i];
            else{
                num[count] = '\0'; count = 0;
                int n = atoi(num);
                switch(op_pre)
                {
                    case '+': S.push(n); break;
                    case '-': S.push(-n); break;
                    case '*': res = S.top(); res*=n; S.pop(); S.push(res); break;
                    case '/': res = S.top(); res/=n; S.pop(); S.push(res); break;
                    default: S.push(n); break;
                }
                op_pre = str[i];
            }
        }
        res = 0;
        while(!S.empty())
        {
            res += S.top();
            S.pop();
        }
        printf("%.2lf\n",res);
    }
    return 0;
}

说明:用了网上一种很好的思路自己实现了一下,就是将数不停存入栈中,如果运算符是*,则将乘的计算结果存入栈,如果运算符是/,则将除的计算结果存入栈,如果是-,则存入负数,最后将栈中的数字相加。
注意:值得注意的一点是这里遇到的运算符决定的是对后面遇到的数如何处理,代码中op_pre就是用来实现这一点。


题目1108:堆栈的使用

#include <iostream>
#include <stack>

using namespace std;

stack<int> S;
int main()
{
    int n;
    while(cin>>n)
    {
        if(n==0) return 0;
        int num;
        for(int i=0; i<n; i++)
        {
            char ch;
            cin>>ch;
            switch(ch)
            {
                case 'P': cin>>num; S.push(num); break;
                case 'A': if(S.empty()) cout<<'E'<<endl;
                          else cout<<S.top()<<endl;
                          break;
                case 'O': if(!S.empty()) S.pop();
            }
        }
        cout<<endl;
        while(!S.empty())   S.pop();  //记得清空
    }
    return 0;
}

注意:由于多组数据是分开的,所以在每组数据结束后要清空栈。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值