zoukankan      html  css  js  c++  java
  • LeetCode 8. 字符串转换整数 (atoi)

    题目描述:

    解法一:

    class Solution {
    public:
        int myAtoi(string str) {
            int index=0;
            bool neg=0;
            long long res=0;
            while(str[index]==' ') index++;
            if(str[index]!='-'&&str[index]!='+'&&(str[index]>'9'||str[index]<'0'))
                return 0;
            if(str[index]=='-') {neg=1;index++;}
            else if(str[index]=='+') index++;
            while(str[index]<='9'&&str[index]>='0'){
                if((neg==0)&&(res>INT_MAX/10||(res==INT_MAX/10&&(str[index]-'0')>7))) return INT_MAX;
                if((neg==1)&&(res>INT_MAX/10||(res==INT_MAX/10&&(str[index]-'0')>8))) return INT_MIN;
                res=res*10+(str[index]-'0');
                index++;
            }
            return neg? -res:res;
        }
    };

    解法二:

    class Solution {
    public:
        int myAtoi(string str) {
            int res=0;
            istringstream is(str);
            is>>res;
            return res;
        }
    };

  • 相关阅读:
    Alpha冲刺Day10
    Alpha冲刺Day9
    Alpha冲刺Day8
    Alpha冲刺Day7
    Alpha冲刺Day6
    SDN
    【Alpha
    【Alpha】团队课程展示
    【Alpha】团队项目测试报告与用户反馈
    【Alpha】总结
  • 原文地址:https://www.cnblogs.com/oneDongHua/p/14264020.html
Copyright © 2011-2022 走看看