字符串转换为对应整数

题目描述
计算逆波兰式(后缀表达式)的值
运算符仅包含"+" , * " - " , " * " 和 " / “,被操作数可能是整数或其他表达式*
例如:
[“20”, “10”, “+”, “30”, " * " ] -> ((20 + 10) * 30) -> 900
[ “40”, “130”, “50”, “/”, “+”] -> (40 + (130 / 50)) -> 42
示例1
输入
[ “20”,“10”,”+",“30”,"*"]
返回值
900

第一种方法:

  1. 将数字字符串转换为整数
    atoi(const char *__nptr) 函数 ; 函数里的参数要为C语言字符串形式例如:将string s;中s转换为C语言字符串形式,可以使用函数 (string).c_str( ) 进行转换;
    库函数原型:
    #inclue <stdlib.h>
    int atoi(const char *nptr);
    用法:将字符串里的数字字符转化为整形数。返回整形值。
    注意:转化时跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时(’/0’)才结束转换,并将结果返回。
class Solution {
public:
    /**
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
    int evalRPN(vector<string>& tokens) {
        stack<int>s;
        int c;
        for(int i = 0;i<tokens.size();i++)
        {
            if(tokens[i]=="+")
            {
                c = s.top();s.pop();c+=s.top();s.pop();s.push(c);
             }else if(tokens[i]=="-")
            {
                c = s.top();s.pop();c=s.top()-c;s.pop();s.push(c);
             }else if(tokens[i]=="*")
            {
                c = s.top();s.pop();c*=s.top();s.pop();s.push(c);
             }else if(tokens[i]=="/")
            {
                c = s.top();s.pop();c=s.top()/c;s.pop();s.push(c);
             }else {
                s.push(atoi(tokens[i].c_str()));
              }
         }
        return s.top();
    }
};

2 . stoi(const string &__str)函数,无需将string类型转换为C语言字符数组类型。

class Solution {
public:
    /**
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
    int evalRPN(vector<string>& tokens) {
        // write code here
        if(tokens.empty()){
            return 0;
        }
        stack<int> sq;
        for(int i=0;i<tokens.size();i++){
            if(tokens[i]!="+"&&tokens[i]!="-"&&tokens[i]!="*"&&tokens[i]!="/"){
                sq.push(stoi(tokens[i]));
            }
            else{
                int a = sq.top();
                sq.pop();
                int b = sq.top();
                sq.pop();
                if(tokens[i]=="+"){
                    b = b + a;
                }
                else if(tokens[i]=="-"){
                    b = b - a;
                }
                else if(tokens[i]=="*"){
                    b = b * a;
                }
                else{
                    b = b / a;
                }
                sq.push(b);
            }
        }
        return sq.top();
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值