Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fa5f01e

Browse files
committed
Solve #227
1 parent baeee41 commit fa5f01e

File tree

2 files changed

+103
-0
lines changed

2 files changed

+103
-0
lines changed

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,4 @@ mod n0222_count_complete_tree_nodes;
194194
mod n0224_basic_calculator;
195195
mod n0225_implement_stack_using_queues;
196196
mod n0226_invert_binary_tree;
197+
mod n0227_basic_calculator_ii;

‎src/n0227_basic_calculator_ii.rs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/**
2+
* [227] Basic Calculator II
3+
*
4+
* Implement a basic calculator to evaluate a simple expression string.
5+
*
6+
* The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
7+
*
8+
* Example 1:
9+
*
10+
*
11+
* Input: "3+2*2"
12+
* Output: 7
13+
*
14+
*
15+
* Example 2:
16+
*
17+
*
18+
* Input: " 3/2 "
19+
* Output: 1
20+
*
21+
* Example 3:
22+
*
23+
*
24+
* Input: " 3+5 / 2 "
25+
* Output: 5
26+
*
27+
*
28+
* Note:
29+
*
30+
*
31+
* You may assume that the given expression is always valid.
32+
* Do not use the eval built-in library function.
33+
*
34+
*
35+
*/
36+
pub struct Solution {}
37+
38+
// submission codes start here
39+
40+
impl Solution {
41+
pub fn calculate(s: String) -> i32 {
42+
let mut acc = 0_i64;
43+
let mut prev = 0_i64;
44+
let mut curr = 0_i64;
45+
let mut sign = 1;
46+
let mut has_prev = false;
47+
let mut multiple = true;
48+
for ch in s.chars() {
49+
match ch {
50+
'0'...'9' => { curr = 10 * curr + (ch as u8 - '0' as u8) as i64; },
51+
'+' | '-' => {
52+
if has_prev {
53+
if multiple {
54+
curr = prev * curr;
55+
} else {
56+
curr = prev / curr;
57+
}
58+
has_prev = false;
59+
}
60+
acc += curr * sign;
61+
curr = 0;
62+
sign = if ch == '+' { 1 } else { -1 };
63+
}
64+
'*' | '/' => {
65+
if has_prev {
66+
if multiple {
67+
curr = prev * curr;
68+
} else {
69+
curr = prev / curr;
70+
}
71+
}
72+
has_prev = true;
73+
prev = curr;
74+
curr = 0;
75+
multiple = if ch == '*' { true } else { false };
76+
},
77+
_ => {},
78+
}
79+
}
80+
if has_prev {
81+
if multiple {
82+
curr = prev * curr;
83+
} else {
84+
curr = prev / curr;
85+
}
86+
}
87+
acc += sign * curr;
88+
acc as i32
89+
}
90+
}
91+
92+
// submission codes end
93+
94+
#[cfg(test)]
95+
mod tests {
96+
use super::*;
97+
98+
#[test]
99+
fn test_227() {
100+
assert_eq!(Solution::calculate("3+2*2".to_owned()), 7);
101+
}
102+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /