QUTOJ 简单的计算式(水)

本文介绍了一种处理包含加法和乘法的简单数学表达式的方法,通过将数字和运算符分离并利用栈来计算表达式的值。文章提供了一个具体的实现案例,包括输入输出示例及代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:http://115.28.203.224/problem.php?cid=1012&pid=6

G: 简单的计算式

时间限制: 1 Sec   内存限制: 128 MB
提交: 38   解决: 7

题目描述

给你一个表达式,式子只有加号和乘号,让你输出结果。


输入

第一行输入一个T,代表T组数据。(输入保证没有多余空格)

接着T行,每行一个字符串,代表一个表达式(只含有+ *)

字符串长度<=1000


输出

对应每行输出一个结果。

样例输入

2
1+3*3+4
4*3*5+8

样例输出

14
68

提示

结果保证在int范围内。

思路:比赛题,很简单,把数字和字符分到两个数组中计算

比完赛想到了栈,如果有除法的话确实需要栈,但是加乘不需要了~

代码:

#include <iostream>
#include<stdlib.h>>
#include<stdio.h>
#include<cmath>
#include<string>
#include<string.h>
#include<queue>
#include<stack>>
using namespace std;
const int maxn = 10000+10;
const int INF = 1e9;
 
int n;
char str[maxn];
int s[maxn];
char ch[maxn];
int k;
int j;
void init(){
    int len = strlen(str);
    int sum = 0;
    k = 0;
    j = 0;
    for(int i = 0;i<len;i++){
        if(str[i]>='0'&&str[i]<='9'){
            sum = sum*10+(str[i]-'0');
            if(str[i+1]<'0' || str[i+1]>'9'){
                s[k] = sum;
                k++;
                sum = 0;
            }
        }
        else {
            ch[j] = str[i];
            j++;
        }
    }
}
int main(){
    scanf("%d",&n);
    while(n--){
        int ans = 0;
        scanf("%s",str);
        init();
        for(int l = 0;l<j;l++){
            if(ch[l]=='*') {
                s[l+1] = s[l]*s[l+1];
                s[l] = 0;
            }
        }
        for(int l = 0;l<k;l++)
            ans +=s[l];
        printf("%d\n",ans);
    }
 
}

石万东学长的队列代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#define inf 0x3f3f3f3f
#define met(a,b) memset(a,b,sizeof a)
#define pb push_back
typedef long long ll;
using namespace std;
const int N = 1050;
const int M = 24005;
const int mod=1e9+7;
int n,m;
int a[N][N];
int main() {
    int t;
    stack<ll>q;
    scanf("%d",&t);
    while(t--){
        while(!q.empty())q.pop();
        char str[1008];
        scanf("%s",str);
        ll now=0,t=1;
        for(int i=0;i<strlen(str);i++){
            if(str[i]>='0'&&str[i]<='9'){
                now=now*10+str[i]-'0';
            }
            else if(str[i]=='+')q.push(t*now),now=0,t=1;
            else if(str[i]=='*'){
                t*=now;
                now=0;
            }
        }
        q.push(t*now);
        ll ans=0;
        while(!q.empty()){
            ans+=q.top();q.pop();
        }
        printf("%lld\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值