zoukankan      html  css  js  c++  java
  • 【LeetCode】227. Basic Calculator

    Problem:

    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.

    Solution:

    字符串分成两种情况:数字num和运算符op,结果设为res,考虑到先乘除后加减的运算法则,设中间数mid优先计算乘除,再与res相加.

    *> C++ version

     1 class Solution {
     2 public:
     3     int calculate(string s) 
     4     {
     5        int res=0, num=0, op='+', i=0, mid=0;
     6        while(i<s.size())
     7        {
     8            num = 0;  ////每一轮要初始化num
     9            //获取一整个数字存储在num中
    10            if(isdigit(s[i]))
    11            {
    12                 while(i<s.size()&&isdigit(s[i]))  //连续数字字符作一个数 
    13                 {   
    14                      num = num*10+(s[i]-'0');
    15                      i++;
    16                 }
    17         
    18                //获取运算符存储在op中
    19                 if(op=='+'||op=='-')
    20                 {
    21                     res = res+mid;
    22                     mid = num*(op=='-'?-1:1);
    23                 }     
    24                 else if(op=='/')
    25                 {
    26                     mid = mid/num;
    27                 }
    28                 else if(op=='*')
    29                 {
    30                     mid = mid*num;
    31                 }
    32            }
    33            else if(s[i]==' ')         //不要漏了开头空格这种情况= - =它喵被摆了一道
    34                 i++;
    35            else     
    36            {
    37                 op=s[i];
    38                 i++;
    39            }
    40        } 
    41         res = res+mid;
    42         return res;
    43     }
    44 };    
  • 相关阅读:
    NAVICAT 拒绝链接的问题
    .net垃圾回收-原理浅析
    C#中标准Dispose模式的实现
    Windbg调试托管代码
    C#泛型基础
    .Net垃圾回收和大对象处理
    C++ 小知识点
    C++之虚函数表
    C++之指针与引用,函数和数组
    C++之const关键字
  • 原文地址:https://www.cnblogs.com/liez/p/5477587.html
Copyright © 2011-2022 走看看