In the Mathematical world of Dr. Ramanujam, every new student must have to pass a exam to take the classes of Advance mathematics from Dr. Ramanujam.
One day Ram wants to have classes of Advance mathematics, so he arrived at class of Dr. Ramanujam. He asked Ram to solve a given mathematical expression then only he will be eligible to take classes. Mathematical expression is in a string form of numbers(0-9) and operators(+,-,*). Dr. Ramanujam asked him to find the answer of the expression but there is a twist that, he does not want him to follow "Operator precedence rule", rather he have his own precedence rule in which he need to operate operations from right to left.
For eg: Given string 2 + 3 * 5 , So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5.
He asked him to solve as fast as possible. So Ram needs your help to solve the expression.
INPUT:
First line contain test cases T. Next T lines contain one string.
1<=T<=100
1<=Length of the String(L)<=31
OUTPUT:
2
2+3*5
1*2*3
Sample Output:
One day Ram wants to have classes of Advance mathematics, so he arrived at class of Dr. Ramanujam. He asked Ram to solve a given mathematical expression then only he will be eligible to take classes. Mathematical expression is in a string form of numbers(0-9) and operators(+,-,*). Dr. Ramanujam asked him to find the answer of the expression but there is a twist that, he does not want him to follow "Operator precedence rule", rather he have his own precedence rule in which he need to operate operations from right to left.
For eg: Given string 2 + 3 * 5 , So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5.
He asked him to solve as fast as possible. So Ram needs your help to solve the expression.
INPUT:
First line contain test cases T. Next T lines contain one string.
1<=T<=100
1<=Length of the String(L)<=31
OUTPUT:
Answer of the given expression.
Sample Input:2
2+3*5
1*2*3
Sample Output:
17
6
http://www.codechef.com/problems/MATHS
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<map>
#include<cmath>
#include<vector>
#include<stdlib.h>
#include<cstdio>
#define ll long long
using namespace std;
int main(){
long int t,i,l,x;
scanf("%ld",&t);
while(t--){
string x;
cin>>x;
l=x.length();
int a=0;
for(int i=l-1;i>=0;--i){
if(x[i]=='*'||x[i]=='+'||x[i]=='-'){
int p=i+1;
while(p<l&&x[p]>='0'&&x[p]<='9'){
a=a*10+x[p]-'0';
p++;
}
break;
}
}
for(int i=l-1;i>=1;--i){
if(x[i-1]=='*'){
int b=0,p=1,w=i-2;
while(w>=0&&x[w]>='0'&&x[w]<='9'){
b+=p*(x[w]-'0');
p*=10;
w--;
}
a=a*b;
}
if(x[i-1]=='+'){
int b=0,p=1,w=i-2;
while(w>=0&&x[w]>='0'&&x[w]<='9'){
b+=p*(x[w]-'0');
p*=10;
w--;
}
a=a+b;
}
if(x[i-1]=='-'){
int b=0,p=1,w=i-2;
while(w>=0&&x[w]>='0'&&x[w]<='9'){
b+=p*(x[w]-'0');
p*=10;
w--;
}
a=a-b;
}
}
printf("%d\n",a);
}
return 0;
}
本文介绍了一种特殊的数学表达式求解方法,该方法要求从右至左进行运算,而非遵循传统的运算符优先级规则。通过示例演示了如何实现这一过程,并提供了一段C++代码作为解决方案。
626

被折叠的 条评论
为什么被折叠?



