您的位置:首页 > 其它

640. Solve the Equation

2018-01-14 03:16 323 查看
1. Description

Given a string representing an equation, solve the equation.

2. Solution

Decode the string, put all 'x's into the left part of the equation, and put all numbers into the right part.

Judge whether there is a solution and return the solution.

3.Code

string solveEquation(string s) {
int a=0;
int b=0;
s=s+"+";
int n=s.size();
bool f=true;
string str;
bool add=true;
for(int i=0;i<n;i++){
if(s[i]=='+'||s[i]=='-'||s[i]=='='){
if(s[i-1]=='x'){
str = str.substr(0,str.size()-1);
int cnt;
if(str=="")
cnt=1;
else
cnt = atoi(str.c_str());
if(!add)
cnt=-cnt;
if(f)
a+=cnt;
else
a-=cnt;
}
else{
int cnt = atoi(str.c_str());
if(!add)
cnt=-cnt;
if(f)
b-=cnt;
else
b+=cnt;
}
if(s[i]=='=')
f=false;

if(s[i]=='-')
add=false;
else
add=true;
str="";
}
else
str+=s[i];
}

if(a==0&&b==0)
return "Infinite solutions";
else if(a==0)
return "No solution";
else
return "x="+to_string(b/a);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Math