File tree 2 files changed +75
-0
lines changed
2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change @@ -8,6 +8,7 @@ mod s0136_single_number;
8
8
mod s0622_design_circular_queue;
9
9
mod s0623_add_one_row_to_tree;
10
10
mod s0636_exclusive_time_of_function;
11
+ mod s0640_solve_the_equation;
11
12
mod s0761_special_binary_string;
12
13
mod s0899_orderly_queue;
13
14
mod s1374_generate_a_string_with_characters_that_have_odd_counts;
Original file line number Diff line number Diff line change
1
+ use std:: num;
2
+
3
+ /**
4
+ * [640] solve the equation
5
+ * https://leetcode.cn/problems/solve-the-equation/
6
+ */
7
+
8
+ pub struct Solution { }
9
+
10
+ impl Solution {
11
+ pub fn solve_equation ( equation : String ) -> String {
12
+ let mut factor = 0 ;
13
+ let mut value = 0 ;
14
+ let mut sign1 = 1_i32 ;
15
+ let mut index = 0 ;
16
+ let len = equation. len ( ) ;
17
+ let chars: Vec < char > = equation. chars ( ) . collect ( ) ;
18
+
19
+ while index < len {
20
+ // 判断是否为等号,更改默认系数
21
+ if chars[ index] == '=' {
22
+ sign1 = -1 ;
23
+ index += 1 ;
24
+ continue ;
25
+ }
26
+
27
+ let mut sign2 = sign1;
28
+ let mut number = 0_i32 ;
29
+ let mut valid = false ;
30
+ // 判断是否为正负号,设置当前项的系数
31
+ if chars[ index] == '-' || chars[ index] == '+' {
32
+ sign2 = if chars[ index] == '-' { -sign1 } else { sign1 } ;
33
+ index += 1 ;
34
+ }
35
+
36
+ // 判断是否为合法数字,并进行累加
37
+ while index < len && chars[ index] . is_digit ( 10 ) {
38
+ number = number * 10 + chars[ index] . to_digit ( 10 ) . unwrap ( ) as i32 ;
39
+ index += 1 ;
40
+ valid = true ;
41
+ }
42
+
43
+ // 判断是否为变量x,并设置对 factor 累加
44
+ if index < len && chars[ index] == 'x' {
45
+ factor += if valid { number * sign2 } else { sign2 } ;
46
+ index += 1 ;
47
+ } else {
48
+ value += sign2 * number;
49
+ }
50
+ }
51
+ if factor == 0 {
52
+ if value == 0 {
53
+ "Infinite solutions" . to_string ( )
54
+ } else {
55
+ "No solution" . to_string ( )
56
+ }
57
+ } else {
58
+ format ! ( "x={:}" , ( -value / factor) )
59
+ }
60
+ }
61
+ }
62
+
63
+ #[ cfg( test) ]
64
+ mod tests {
65
+ use super :: * ;
66
+
67
+ #[ test]
68
+ fn test_640 ( ) {
69
+ assert_eq ! (
70
+ Solution :: solve_equation( "x+5-3+x=6+x-2" . to_string( ) ) ,
71
+ "x=2" . to_string( )
72
+ )
73
+ }
74
+ }
You can’t perform that action at this time.
0 commit comments