输入为一行字符串,即一个表达式。其中运算符只有-,+,*。参与计算的数字只有0~9. 保证表达式都是合法的,排列规则如样例所示。
输出一个数,即表达式的值
3+5*7
56
#include <stdio.h> #include <string.h> #define N 50 int main(){ char str[N]; gets(str); int result=str[0]-'0'; //得到第0个字符,并减去字符'0'使其转换成数字 int i,temp; for(i=1;i<strlen(str)-1;i+=2){ //从第二个字符开始算 temp=str[i+1]-'0'; //要操作的数 if(str[i]=='+'){ result+=temp; //结果 }else if(str[i]=='-'){ result-=temp; }else if(str[i]=='*'){ result*=temp; } } printf("%d\n",result); return 0; }
package go.jacob.day914; import java.util.Scanner; public class Demo3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int sum = s.toCharArray()[0] - '0'; for (int i = 1; i < s.length() - 1; i += 2) { int tmp = s.toCharArray()[i + 1] - '0'; switch (s.toCharArray()[i]) { case '+': sum += tmp; break; case '-': sum -= tmp; break; case '*': sum *= tmp; break; } } System.out.println(sum); sc.close(); } }
#include<bits/stdc++.h> using namespace std; long long ans,n; char a,b; int main() { cin>>a; ans=a-'0'; while(1) { a=getchar(); if(a=='\n'||a==' ') break; b=getchar(); if(a=='+') ans+=(b-'0'); if(a=='-') ans-=(b-'0'); if(a=='*') ans*=(b-'0'); } cout<<ans; return 0; }
package com.coding.wangyi;
import java.util.Scanner;
public class GetValue {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String parnn = s.nextLine();
int ans=parnn.charAt(0) - '0';
for(int i=1; i<parnn.length()-1; i=i+2) {
int num = parnn.charAt(i+1) - '0';
char par = parnn.charAt(i);
switch(par) {
case '+': {
ans = ans + num;
break;
}
case '*':{
ans = ans * num;
break;
}
case '-':{
ans = ans - num;
break;
}
}
}
System.out.println(ans);
}
}
package expression; import java.util.*; /** * 3+5*7 * 先来看这道题的解题步骤: * 1. 当遇到数字3的时候,设置一个变量cur记录下它; * 2. 当遇到'+'时,判断flag的状态,根据flag的状态去更新res。例如,我们设置默认的flag为'+',故res+=cur,得到res=3, * 并且更新flag的状态为当前的字符'+'; * 3. 又遇到数字5,更新cur的值为5; * 4. 遇到符号'*',执行步骤2,根据flag的状态去更新res。由于我们之前的flag为'+',故res+=cur,为3+5=8,得到res=8, * 并且更新flag的状态为当前的字符'*'; * 5. 遇到数字7,更新cur的值为7; * 6. 这时候已经到了表达式的最后了,也执行步骤2,故可以得到res=8*7=56。 * 这道题的难点就在于: * 第一个数是负数怎么处理?-3+5*7 * 可以看到代码中,当第一个数为负数的时候,则第一个字符为'-',故flag的状态更新为了'-'。 * 再遇到3的时候,更新cur的值为3,再遇到字符'+',先根据flag的状态执行res-=cur,得到res=-3. * 后面步骤的就跟之前的一样了。 * @author 何嘉龙 * */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String str = in.nextLine(); int res = getExpressionVal(str); System.out.println(res); } in.close(); } public static int getExpressionVal(String str) { char[] chas = str.toCharArray(); int res = 0; int cur = 0; char flag = '+'; for (int i = 0; i < chas.length; i++) { if (chas[i] < '0' || chas[i] > '9' || i == chas.length - 1) { if (i == chas.length - 1) { cur = chas[i] - '0'; } if (flag == '+') { res += cur; } else if (flag == '-') { res -= cur; } else { res *= cur; } flag = chas[i]; } else { cur = chas[i] - '0'; } } return res; } }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); sc.close(); int tmp = s.charAt(0) - '0'; for (int i = 1; i < s.length() - 1; ) { char operate = s.charAt(i); i ++; StringBuilder sb = new StringBuilder(); while ( i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') { sb.append(s.charAt(i)); i ++; } int r = Integer.valueOf(sb.toString()); switch (operate) { case '+': tmp = tmp + r; break; case '-': tmp = tmp - r; break; case '*': tmp = tmp * r; break; case '/': tmp = tmp / r; break; } } System.out.println(tmp); } }
var readline = require('readline'); var rl= readline.createInterface({ input : process.stdin, output : process.stdout }) var num = 0; var mod = "+"; rl.on("line",function(input){ input.replace(/(\d+)([-+*]|)/g,function($0,$1,$2){ $1=~~$1; //对num和$1进行求值运算 第一次是计算0+$1 num=({ "+":num+$1, "-":num-$1, "*":num*$1 }[mod]); //记录下一次的求值方式 mod=$2; return $0; }) console.log(num); num=0; })
关键之处在于:输入的一个数字和下一个数字之间肯定隔着一个操作符,所以在第一个for循环的时候i=i+2,依次取数,再取操作符进行运算。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
cin >> str;
int ans = str[0] - '0';
for (int i = 1; i < str.length() - 1; i += 2)
{
//关键之处i+=2
if (str[i] == '*')
ans = ans * (str[i + 1] - '0');
else if (str[i] == '+')
ans = ans + (str[i + 1] - '0');
else
{
ans = ans - (str[i + 1] - '0');
}
}
cout << ans << endl;
return 0;
}
#include<bits/stdc++.h> using namespace std; int main(){ char str[20]; while(scanf("%s",str)!=EOF){ int num=str[0]-'0';//第一个数字 for(int i=1;i<strlen(str)-1;i+=2){//遍历所有符号位 if(str[i]=='+')num+=str[i+1]-'0'; if(str[i]=='-')num-=str[i+1]-'0'; if(str[i]=='*')num*=str[i+1]-'0'; } cout<<num<<endl; } return 0; }
import sys class Solution: def eval_express(self, strs): stack = list() index = 0 while index < len(strs): if strs[index] not in ['+', '-', '*']: stack.append(strs[index]) index += 1 else: num1 = stack.pop() rs = eval(str(num1)+strs[index:index+2]) stack.append(rs) index += 2 print(stack[0]) if __name__ == '__main__': args = sys.stdin.readline() solution = Solution() solution.eval_express(args)
import java.util.Collections;
import java.util.Scanner;
import java.util.Stack;
/*
* 开始看错了题目,虽然有更加简单的方法,但是还是通用的stack解决
* */
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String line = scanner.nextLine();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c >= '0' && c <= '9') {
int tmp = c - '0';
if (stack.isEmpty()) {
stack.add(tmp);
} else {
int ops = stack.pop();
int pre = stack.pop();
if(ops == 0){
tmp+= pre;
}else if(ops ==1){
tmp = pre - tmp;
}else{
tmp *= pre;
}
stack.add(tmp);
}
} else if (c == '+') {
stack.add(0);
} else if (c == '-') {
stack.add(1);
} else if (c == '*') {
stack.add(2);
}
}
System.out.println(stack.pop());
}
}
}
#include <iostream> #include <string> using namespace std; int main() { string s; cin>>s; int res = s[0]-'0'; for(int i=2;i<s.size();i+=2) { s[i]-='0'; if(s[i-1]=='+') res+=s[i]; else if(s[i-1]=='-') res-=s[i]; else res*=s[i]; } cout<<res; return 0; }
Scanner sc = new Scanner(System.in); System.out.println("请输入表达式"); String eqExp = sc.next(); eqExp = eqExp.trim(); int sum = 0; char lastExp = 0; for (int i = 0;i < eqExp.length();i++) { if (i % 2 == 0) { int num = Integer.parseInt(eqExp.substring(i,i+1)); if (i == 0 ) { sum += num; continue; } if ('+' == lastExp) { sum += num; } else if ('-' == lastExp) { sum -= num; } else if ('*' == lastExp) { sum *= num; } else { System.out.println("表达式有误"); return; } } else { lastExp = eqExp.charAt(i); } } System.out.println(sum);