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进制处理,把结果用加法运算累计起来。

  • 相关阅读:
    (二)Maven的使用--安装配置
    (一)Maven介绍
    (二)Monkey自动化脚本
    App测试--专项测试
    Java基础--(三)运算符
    Vue.js 介绍入门
    NodeJS 入门第三天(Express框架)
    NodeJS 入门第二天(EJS模板)
    《前端架构设计》读后感
    NodeJS 入门第一天
  • 原文地址:https://www.cnblogs.com/ender-cd/p/4611483.html
Copyright © 2011-2022 走看看