Skip to content

Instantly share code, notes, and snippets.

@junddao
Last active October 18, 2022 01:52
Show Gist options
  • Save junddao/7021cf1f5b46ee5bc3bafa65af14848b to your computer and use it in GitHub Desktop.
Save junddao/7021cf1f5b46ee5bc3bafa65af14848b to your computer and use it in GitHub Desktop.
leetcode 227
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