aboutsummaryrefslogtreecommitdiff
path: root/other/basic_calculator.rs
diff options
context:
space:
mode:
Diffstat (limited to 'other/basic_calculator.rs')
-rw-r--r--other/basic_calculator.rs29
1 files changed, 29 insertions, 0 deletions
diff --git a/other/basic_calculator.rs b/other/basic_calculator.rs
new file mode 100644
index 0000000..d33a18c
--- /dev/null
+++ b/other/basic_calculator.rs
@@ -0,0 +1,29 @@
+struct Solution;
+
+impl Solution {
+ pub fn calculate(s: String) -> i32 {
+ let mut sp: Vec<i32> = Vec::new();
+ let (mut ans, mut num, mut sign) = (0, 0, 1);
+ sp.push(sign);
+ for ch in s.chars() {
+ match ch {
+ ' ' => {}
+ '+' | '-' => {
+ ans += num * sign;
+ sign = sp.last().unwrap() * if ch == '+' {1} else {-1};
+ num = 0;
+ }
+ '(' => {sp.push(sign);}
+ ')' => {sp.pop();}
+ _ => {num * 10 + (ch as i32 - '0' as i32)}
+ };
+ }
+ ans += num * sign;
+ ans
+ }
+}
+
+fn main() {
+ let s = String::from("1 + 1");
+ print!("{}", Solution::calculate(s));
+}