求解一个给定的方程,将x以字符串"x=#value"的形式返回。该方程仅包含’+’,’ - '操作,变量 x 和其对应系数。
如果方程没有解,请返回“No solution”。
如果方程有无限解,则返回“Infinite solutions”。
如果方程中只有一个解,要保证返回值 x 是一个整数。
示例 1:
输入: "x+5-3+x=6+x-2"
输出: "x=2"
示例 2:
输入: "x=x"
输出: "Infinite solutions"
示例 3:
输入: "2x=x"
输出: "x=0"
示例 4:
输入: "2x+3x-6x=x+2"
输出: "x=-1"
示例 5:
输入: "x=x+2"
输出: "No solution"
解题思路:方程化简的基本形式是左边是未知数XXX,右边是常数CCC,所以把字符串按===切割,生成两个变量x,cx,cx,c,分成左右两边,从向右遍历,左边遇到未知数xxx时,x+1x+1x+1,右边遇到则x−1x-1x−1,对c而言同样如此。
class Solution:
def solveEquation(self, equation: str) -> str:
left_equation, right_equation = equation.split('=')
x = 0
c = 0
# 左边切分
if left_equation[0] != '-':
left_equation = '+' + left_equation
left_equation += '+'
temp = 0
for i in range(1,len(left_equation)):
if left_equation[i] == '+' or left_equation[i] == '-':
# 含有x 存在
if left_equation[i-1] == 'x':
b = left_equation[temp:i - 1]
if len(b) == 1:
b += '1'
x += int(b)
else:
c -= int(left_equation[temp:i])
temp = i
# 右边边切分
if right_equation[0] != '-':
right_equation = '+' + right_equation
right_equation += '+'
temp = 0
for i in range(1,len(right_equation)):
if right_equation[i] == '+' or right_equation[i] == '-':
# 含有x 存在
if right_equation[i-1] == 'x':
b = right_equation[temp:i-1]
if len(b) == 1:
b += '1'
x -= int(b)
else:
c += int(right_equation[temp:i])
temp = i
if x == 0 and c == 0:
return 'Infinite solutions'
elif x == 0 and c != 0:
return 'No solution'
else:
ans = c/x
if ans == -0.0:
ans = 0
return 'x=%.0f'%(ans)