解题思路:遍历字符串,对于不同的字符执行不同的操作,模拟操作
#
# @lc app=leetcode.cn id=640 lang=python3
#
# [640] 求解方程
#
# @lc code=start
from curses.ascii import isdigit
class Solution:
def solveEquation(self, equation: str) -> str:
factor = val = 0
i, n, sign = 0, len(equation), 1 # 等式左边默认系数为正
while i < n:
if equation[i] == '=':
sign = -1
i += 1
continue
s = sign
if equation[i] == '+':
i += 1
elif equation[i] == '-':
s = -s
i += 1
num, valid = 0, False
while i < n and equation[i].isdigit():
valid = True
num = num*10+int(equation[i])
i += 1
if i < n and equation[i] == 'x': # 变量
factor += s*num if valid else s
i += 1
else: # 数值
val += s*num
if factor == 0:
return "No solution" if val else "Infinite solutions"
return f"x={-val//factor}"
# @lc code=end
class Solution {
public:
string solveEquation(string equation) {
int factor=0,val=0;
int index=0,n=equation.size(),sign=1;//等式左边系数为正
while(index<n){
if (equation[index]=='='){
index+=1;
sign=-1;//等式右边系数为负
continue;
}
int s=sign,number=0;
bool valid=false; //记录num是否有效
if(equation[index]=='-'||equation[index]=='+'){
s=(equation[index]=='-')? -sign:sign;
index++;
}
while(index<n&&isdigit(equation[index])){
number=number*10+(equation[index]-'0');
index++;
valid=true;
}
if(index<n&&equation[index]=='x'){
factor+=valid? s*number:s;
index++;
}
else{
val+=s*number;
}
}
if (factor==0){
return val==0? "Infinite solutions":"No solution";
}
return string("x=")+to_string(-val/factor);
}
};