zoukankan      html  css  js  c++  java
  • 练习题 (四)

    题目:

    Basic Calculator II

    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
    

    Note: Do not use the eval built-in library function.

    解答:

    class Solution {
    public:
        int calculate(string s) {
            int result = 0, status = 1, term = 0;
            for (int i = 0; i < s.length(); ++i) {
                if(s[i] == '+') {
                    status = 1;
                    result += term;
                    term = 0;
                }
                else if(s[i] == '-') {
                    status = 2;
                    result += term;
                    term = 0;
                }
                else if(s[i] == '*') {
                    status = 3;
                }
                else if(s[i] == '/') {
                    status = 4;
                }
                else if (isdigit(s[i])) {
    
                    int x = 0;
                    for (; isdigit(s[i]); ++i) {
                        x = x * 10 + s[i] - '0';
                    }
                    -- i;
    
                    switch(status) {
                        case 1:
                            term = x;
                            break;
    
                        case 2:
                            term = -x;
                            break;
    
                        case 3:
                            term *= x;
                            break;
    
                        case 4:
                            term /= x;
                            break;
    
                    }
                }
            }
    
            return result + term;
        }
    };

    还是C++的解答明了,扫描一遍的过程中,记住了符号,对连续数字的10进制处理,把结果用加法运算累计起来。

  • 相关阅读:
    sort color (荷兰国旗)
    先序遍历和后序遍历构建二叉树
    二叉树的遍历
    排序
    内存相关内容
    chrome控制台console方法表
    记一次移动端CSS引发的小Bug
    JavaScript的事件
    浅谈webpack打包原理
    JS模块化进程
  • 原文地址:https://www.cnblogs.com/ender-cd/p/4611483.html
Copyright © 2011-2022 走看看