P1689 Equation Solver

Description Title
to an equation of the form X + Y = Z or XY = Z. Wherein given two unknowns, a third request number. Unknown use '?' Indicates, the equation may be some extra space.

Enter the format
line equation.

Output format
'?' Represents value

Sample input and output
Input # 1 replication
sample input 1
1 + 2 =?

Sample input 2
3 +? = 2
Output # 1 replication
sample output 1
3

Sample Output 1
-1
Description / Tips
0 <= X, Y, Z <1,000,000,000

#include<bits/stdc++.h>
using namespace std;
string s;
long long x, y, z;
char ch;
int main(){
	getline(cin , s);
	int i = 0, len = s.size(), flag = 1;
	while(i < len){
		if(flag == 1){//x:第一项数字
			if(isdigit(s[i]))
				x = x * 10 + s[i]-'0';
			else if(s[i] == '?')
				x = -1;
		}else if(flag == 0){//y:第二项数字
			if(isdigit(s[i])){
				y = y * 10 + s[i]-'0';
			}else if(s[i] == '?')
				y = -1;
		}else if(flag == -1){//z:等于号后面的数字
			if(isdigit(s[i]))
				z = z * 10 + s[i]-'0';
			else if(s[i] == '?')
				z = -1;
		}
		if(s[i] == '+' || s[i] == '-')//ch:运算符
			ch = s[i],flag = 0;
		else if(s[i] == '=')
			flag = -1;
		i++;	
	}
	//运算结果
	if(x == -1){
		if(ch == '+')
			cout << z - y;
		else if(ch == '-')
			cout << z + y;
	}else if(y == -1){
		if(ch == '+')
			cout << z - x;
		else if(ch == '-')
			cout << x - z;
	}else if(z == -1){
		if(ch == '+')
			cout << x + y;
		else if(ch == '-') 
			cout << x - y;
	}
	return 0;
} 

Question: how the code a little shorter.

Published 15 original articles · won praise 10 · views 215

Guess you like

Origin blog.csdn.net/qq_39053800/article/details/104237059