Math-640-Solve the Equation
2018-01-29 17:03
429 查看
Description:
Solve a given equation and return the value of x in the form of string “x=#value”. The equation contains only ‘+’, ‘-’ operation, the variable x and its coefficient.
If there is no solution for the equation, return “No solution”.
If there are infinite solutions for the equation, return “Infinite solutions”.
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Best Solution:
Solve a given equation and return the value of x in the form of string “x=#value”. The equation contains only ‘+’, ‘-’ operation, the variable x and its coefficient.
If there is no solution for the equation, return “No solution”.
If there are infinite solutions for the equation, return “Infinite solutions”.
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2" Output: "x=2"
Example 2:
Input: "x=x" Output: "Infinite solutions"
Example 3:
Input: "2x=x" Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2" Output: "x=-1"
Example 5:
Input: "x=x+2" Output: "No solution"
Best Solution:
class Solution { public String solveEquation(String equation) { if(equation == null || equation.length() == 0) return "No solution"; String[] sides = equation.split("="); int[] left = parse(sides[0]), right = parse(sides[1]); if(left[0] == right[0]) { if(left[1] == right[1]) return "Infinite solutions"; return "No solution"; } int val = (right[1]-left[1])/(left[0]-right[0]); return "x="+val; } private int[] parse(String s) { int sign = 1, val = 0; int[] res = new int[2]; for(int i=0; i<s.length(); i++) { char c = s.charAt(i); if(c=='x') { if(i == 0) res[0]++; else if(s.charAt(i-1) == '-' || s.charAt(i-1) == '+') res[0] += sign; else res[0] += sign * val; val = 0; } else if(c == '-' || c == '+') { res[1] += sign * val; val = 0; sign = c == '-' ? -1 : 1; } else { val = val * 10 + c - '0'; } } res[1] += sign * val; return res; } }
相关文章推荐
- 640. Solve the Equation
- LeetCode 640 : Solve the Equation(python)
- 640. Solve the Equation
- 640. Solve the Equation
- 640. Solve the Equation
- [LeetCode] Solve the Equation 解方程
- leetcode 640. Solve the Equation
- LeetCode Weekly Contest 40(2) - Solve the Equation
- Solve the Equation问题及解法
- hdu 2199~Can you solve the equation?~二分法求解
- Use the BFS to solve the equation problems(Case : hdu 4403 )
- [leetcode]640. Solve the Equation
- Solve the Equation
- Solve the Equation
- Can you solve the equation?(二分求方程解)
- Can you solve this equation?
- HDUOJ2199 Can you solve this equation?
- Can you solve this equation?(二分查找的简单应用)
- The Most Important Algorithms (in CS and Math)
- Can you solve this equation(二分)