Created with <3 with dartpad.dev.
Last active
October 18, 2022 01:52
-
-
Save junddao/7021cf1f5b46ee5bc3bafa65af14848b to your computer and use it in GitHub Desktop.
leetcode 227
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
Solution solution = Solution(); | |
print(solution.calculate("14-3/2")); | |
} | |
class Solution { | |
int calculate(String s) { | |
List<String> chs = s.split(''); | |
int result = 0; | |
List<int> stack = []; | |
String prevChar = 'a'; | |
String operator = 'a'; | |
int number = 0; | |
for(int i = 0 ; i < chs.length ; i++){ | |
if(chs[i] == ' ') { | |
continue; | |
} | |
if(chs[i].codeUnitAt(0) >= '0'.codeUnitAt(0) && chs[i].codeUnitAt(0) <= '9'.codeUnitAt(0)){ | |
if(prevChar.codeUnitAt(0) >= '0'.codeUnitAt(0) && prevChar.codeUnitAt(0) <= '9'.codeUnitAt(0)){ | |
number= (number * 10) + int.parse(chs[i]); | |
} | |
else{ | |
number = int.parse(chs[i]); | |
} | |
} | |
else { | |
if(operator == 'a'){ | |
stack.add(number); | |
} | |
if(operator == '+'){ | |
stack.add(number); | |
} | |
else if(operator == '-'){ | |
stack.add(-number); | |
} | |
else if(operator == '*'){ | |
stack.add(number * stack.removeLast()); | |
} | |
else if(operator == '/'){ | |
stack.add(stack.removeLast() ~/ number); | |
} | |
operator = chs[i]; | |
number = 0; | |
} | |
prevChar = chs[i]; | |
} | |
if(operator == 'a'){ | |
stack.add(number); | |
} | |
if(operator == '+'){ | |
stack.add(number); | |
} | |
else if(operator == '-'){ | |
stack.add(-number); | |
} | |
else if(operator == '*'){ | |
stack.add(number * stack.removeLast()); | |
} | |
else if(operator == '/'){ | |
stack.add(stack.removeLast() ~/ number); | |
} | |
print(stack); | |
for(int n in stack){ | |
result = result + n; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment