原题:
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”
思路:
本题要求求解方程组,并且假定方程组只有加和减两种运算,同时只含有x一个未知数。
解题的思路是:(1)先把等式分割为左右两边(2)通过mergeEquation函数分别简化左右两边,即计算出左右两侧x的系数和常数值,记为left_xCoefficient,left_constant,right_xCoefficient,right_constant(3)把含有x的项移到左边,把常数项移到右边,其系数分别简化为merged_xCoefficient,merged_constant,然后通过求解方程组的基本知识分类求出答案。
本题考查字符串、list的一些操作和求解方程组的数学知识,测试的时候要充分考虑各种情况。
代码:
class