File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change @@ -411,4 +411,75 @@ class Solution(object):
411
411
return False
412
412
```
413
413
414
+ ## 640. 求解方程
414
415
416
+ [ 原题链接] ( https://leetcode-cn.com/problems/solve-the-equation/ )
417
+
418
+ ### 思路
419
+
420
+ 求解方程就是要把方程简化,求出 ` x ` 的个数 ` x_count ` 和剩余数值 ` num ` :
421
+
422
+ ```
423
+ x_count * x = num
424
+ ```
425
+
426
+ 最终需要求的结果就是 ` num / x_count ` 。
427
+
428
+ 我们可以把方程式根据等号分为左右两个式子,对左右两个式子进行遍历,分别求出 ` x ` 的数量和剩余数值。
429
+
430
+ 在遍历过程中:
431
+
432
+ 1 . 遇到字符为 ` + ` 或 ` - ` (即遇到运算符):对该运算符之前的公式进行结算
433
+ 2 . 遇到字符不是运算符:
434
+ 1 . 遇到字符为 ` x ` :根据 ` x ` 前面跟着的数字和运算符,对 ` x ` 的个数进行结算
435
+ 2 . 遇到字符为数字:把该数字记录下来(我在这里用了 Python 的列表进行记录),当遇到下一个运算符或符号 ` x ` 时进行结算
436
+
437
+ ⚠️注: 会遇到 ` 0x ` 这样的写法。
438
+
439
+ ``` python
440
+ class Solution :
441
+ def solveEquation (self , equation : str ) -> str :
442
+ formula = equation.split(" =" )
443
+
444
+ def get_count (formula ):
445
+ num_list = []
446
+ pre_symbol = " +"
447
+ x_count = 0
448
+ num = 0
449
+ for c in formula:
450
+ # 不是运算符
451
+ if c != " +" and c != " -" :
452
+ if c == " x" :
453
+ add_x = 1 if len (num_list) == 0 else int (" " .join(num_list))
454
+ if pre_symbol == " +" :
455
+ x_count += add_x
456
+ else :
457
+ x_count -= add_x
458
+ num_list = [] # 清空列表
459
+ else :
460
+ # 是数字
461
+ num_list.append(c)
462
+ # 是运算符
463
+ else :
464
+ if len (num_list) != 0 :
465
+ num = eval (str (num) + pre_symbol + " " .join(num_list))
466
+ pre_symbol = c
467
+ num_list = []
468
+ # 最后遗漏的数字
469
+ if len (num_list) != 0 :
470
+ num = eval (str (num) + pre_symbol + " " .join(num_list))
471
+ return [x_count, num]
472
+
473
+ left = get_count(formula[0 ])
474
+ right = get_count(formula[1 ])
475
+
476
+ x_count = left[0 ] - right[0 ]
477
+ num = left[1 ] - right[1 ]
478
+
479
+ # 计算结果
480
+ if x_count == 0 and num == 0 :
481
+ return " Infinite solutions"
482
+ if x_count == 0 and num != 0 :
483
+ return " No solution"
484
+ return " x=" + str (- num // x_count)
485
+ ```
You can’t perform that action at this time.
0 commit comments