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
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-640-Solve the Equation
- LeetCode 640 : Solve the Equation(python)
- 640. Solve the Equation
- 640. Solve the Equation
- 640. Solve the Equation
- Solve the Equation
- Solve the Equation
- Use the BFS to solve the equation problems(Case : hdu 4403 )
- LeetCode Weekly Contest 40(2) - Solve the Equation
- [leetcode]640. Solve the Equation
- leetcode 640. Solve the Equation
- [LeetCode] Solve the Equation 解方程
- hdu 2199~Can you solve the equation?~二分法求解
- Can you solve the equation?(二分求方程解)
- Solve the Equation问题及解法
- Can you solve this equation?
- hdu2199 Can you solve this equation? (二分搜索)
- How to solve "The specified service has been marked for deletion" error
- hdu2199 Can you solve this equation?
- I was trying to solve problem '1234 - Harmonic Number', I wrote the following code