640 求解方程 (中等)

简介:

image-20221030203242964

解题思路:遍历字符串,对于不同的字符执行不同的操作,模拟操作

#
# @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);
    }
};
相关文章
ccfcsp 202312-2 因子化简
ccfcsp 202312-2 因子化简
ccfcsp 202009-2 因子化简
ccfcsp 202009-2 因子化简
|
8月前
考研高数之无穷级数题型一:判断收敛性、求收敛半径以及收敛域和收敛区间(题目讲解)
考研高数之无穷级数题型一:判断收敛性、求收敛半径以及收敛域和收敛区间(题目讲解)
490 0
|
数据安全/隐私保护
闭区间连续函数的性质+习题课(函数与极限总复习)——“高等数学”
闭区间连续函数的性质+习题课(函数与极限总复习)——“高等数学”
|
算法 前端开发
力扣-最接近三数之和 中等 🌍
力扣-最接近三数之和 中等 🌍
134 0
力扣-最接近三数之和 中等 🌍

热门文章

最新文章