首页 > 其他 > 详细

【leetcode】640. Solve the Equation

时间:2018-09-17 18:38:15      阅读:186      评论:0      收藏:0      [点我收藏+]

题目如下:

技术分享图片

解题思路:本题的思路就是解析字符串,然后是小学时候学的解方程的思想,以"2x+3x-6x+1=x+2",先把左右两边的x项和非x项进行合并,得到"-x+1=x+2",接下来就是移项,把x项移到左边,常数项移到右边,得到"2x=-1",最后的解就是x=-1/2。对于任意一个表达式ax+b = cx+d来说,最终都能得到解x=(d-b)/(a-c),这里要对(a-c)是否为0做判断,同时根据(d-b)是否为0等到Infinite solutions,No solution,常规解三种结果。

代码如下:

class Solution(object):
    def parse(self,expression):
        x,v = 0,0
        if expression[0] == -:
            expression = 0 + expression
        item = ‘‘
        operators = [+, -]
        operator = ‘‘
        for i in (expression + #):
            if i in operators or i == #:
                if item == x:
                    item = 1x
                if operator == ‘‘:
                    operator = i
                    if item[-1] == x:
                        x = int(item[:-1])
                    else:
                        v = int(item)
                    item = ‘‘
                else:
                    if operator == + and item[-1] == x:
                        x += int(item[:-1])
                    elif operator == - and item[-1] == x:
                        x -= int(item[:-1])
                    elif operator == + and item[-1] != x:
                        v += int(item)
                    else:
                        v -= int(item)
                    item = ‘‘
                    operator = i
            else:
                item += i
        return x,v
    def solveEquation(self, equation):
        """
        :type equation: str
        :rtype: str
        """
        left,right = equation.split(=)
        lx,lv = self.parse(left)
        rx,rv = self.parse(right)

        if lx - rx == 0 and rv - lv == 0:
            return "Infinite solutions"
        elif lx - rx == 0 and rv - lv != 0:
            return "No solution"
        else:
            return "x=" + str((rv - lv)/(lx - rx))
        

 

【leetcode】640. Solve the Equation

原文:https://www.cnblogs.com/seyjs/p/9660467.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!