美文网首页
[leetcode] 8. String to Integer

[leetcode] 8. String to Integer

作者: Kevifunau | 来源:发表于2018-10-02 22:10 被阅读0次

    这题貌似是实现c++ 内置的atoi


    image.png

    字符串--> 带符号的整数

    1. 去除左边所有的空格
    2. 处理首字符是sign的情况
    3. 把数字字符转化为整数 直到遇到( 1.非数字字符 2. 到头 3. 超过上限)
    #include <cmath>
    class Solution {
    public:
        int myAtoi(string str) {
            
            int first = 0;
            // remove whilespace
            while(str[first] ==' '){
                first++;
            }
            if( first >= str.size()) return 0;
    
            //  +/- 
            int flag = 1;
            if(str[first] == '-'){
                first++;
                flag = 0;
            }else if(str[first]=='+'){
                first++;
            }
            
            long ans = 0;
            int MAX = pow(2,31) -1;
            int MIN = -pow(2,31);
            
            while( first < str.size()){
                if( str[first] <'0' || str[first]>'9' || ans >MAX) break;
                ans = ans*10 + (str[first]-'0') ;
                first++;
            }
            
            if (flag){
                return ans>MAX? MAX :ans;
            }else{
                return -ans<MIN?MIN:-ans;
            }
            
      
        }
    };
    
    image.png

    相关文章

      网友评论

          本文标题:[leetcode] 8. String to Integer

          本文链接:https://www.haomeiwen.com/subject/iniaoftx.html