• LeetCode Basic Calculator II


    DESCIRPTION

    Implement a basic calculator to evaluate a simple expression string.

    The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

    You may assume that the given expression is always valid.

    Some examples:

    "3+2*2" = 7
    " 3/2 " = 1
    " 3+5 / 2 " = 5
    

    SOLUTION

    class Solution {
    public:
        int calculate(string s) {
            char last_op = '+';
            char op = '+';
            int len = s.size();
            int curval = 0;
            int sumval = 0;
            int val = 0;
            int idx = read_number(s, 0, curval);
    
            while (idx < len) {
                idx = read_operator(s, idx, op);
                idx = read_number(s, idx, val);
                if (op == '-' || op == '+') {
                    sumval = last_op == '-' ? sumval - curval : sumval + curval;
                    curval = val;
                    last_op= op;
                } else if (op == '*' || op == '/') {
                    curval = op == '*' ? curval * val : curval / val;
                } else {
                    cout<<"error"<<endl;
                }
            }
            sumval = last_op == '-' ? sumval - curval : sumval + curval;
            return sumval;
        }
        
        int read_number(const string& s, int from, int& val) {
            int len = s.size();
            val = 0;
            from = skip_space(s, from);
            while(from < len && s[from] >= '0' && s[from] <= '9') {
                    val = val * 10 + s[from++] - '0';
            }
            from = skip_space(s, from);
            return from;
        }
        
        int read_operator(const string& s, int from, char& op) {
            from = skip_space(s, from);
            if (from == s.size()) {
                return from;
            } else {
                op = s[from];
                return ++from;  
            }
            from = skip_space(s, from);
        }
        
        int skip_space(const string& s, int from) {
            int len = s.size();
            while (from < len && s[from] == ' ') {
                from++;
            }
            return from;
        }
    };
    

    写的还是有些烦,不过一次AC

  • 相关阅读:
    Ionic Tabs
    Ionic实战九:ionic视频播放
    Ionic实战八:ionic登陆页面源码
    Ionic实战七:Ionic 音乐以及社交页面
    Ionic实战六:日期选择控件
    Ionic实战五:ionic图表源码基于highcharts
    Ionic实战四:ionic 即时通讯_ionic仿雅虎邮箱
    Ionic实战三:Ionic 图片预览可放大缩小左右滑动demo-iClub图片预览
    Ionic实战二:购物车
    编译错误总汇
  • 原文地址:https://www.cnblogs.com/lailailai/p/4597078.html
Copyright © 2020-2023  润新知