zoukankan      html  css  js  c++  java
  • Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

    Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

    题目描述

    实现atoi函数,将一个字符串转化为数字

    测试样例

    Input: "42"
    Output: 42
    
    Input: "   -42"
    Output: -42
    
    Input: "4193 with words"
    Output: 4193
    
    Input: "words and 987"
    Output: 0
    

    详细分析

    这道题的corner cases非常多,请务必确保下面cases都能通过的情况下再提交。

    "42"
    "words and 987"
    "-91283472332"
    "0-1"
    "-000000000000001"
    "  0000000000012345678"
    "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000522545459"
    "-2147483647"
    "-2147483648"
    "2147483648"
    "2147483649"
    ""
    "7"
    "   +0 123"
    

    算法实现

    class Solution {
    public: 
        string trim(const std::string&str){
            string nstr;
            int i=0;
            while(isspace(str[i])){
                i++;
            }
            
            for(;i<str.length();i++){
                if(isspace(str[i])){
                    break;
                }
                nstr +=str[i];
            }
            return nstr;
        }
        
        int myAtoi(string str) {
            str = trim(str);
            if(str.length()==0 || (str[0]!='+'&&str[0]!='-'&& !isdigit(str[0]))){
                return 0;
            }
            
            int i=0;
            
            //consume sign char
            if(str[0] =='+' || str[0]=='-'){
                i++;
            }
            string nstr;
            while(isdigit(str[i])){
                nstr+=str[i];
                i++;
            }
            if(nstr.length()==0){
                return 0;
            }
            i=0;
            // consume meaningless zeros
            while(nstr[i]=='0'){
                i++;
            }
            nstr = nstr.substr(i);
            long long result = 0L;
            unsigned long long exp = 1; 
            for(int k=nstr.length()-1;k>=0;k--){
                result += ((int)(nstr[k]-'0'))*exp;
                
                if(exp> numeric_limits<int>::max()){
                    return str[0]=='-'?numeric_limits<int>::min():numeric_limits<int>::max();
                }
                exp*=10;
                if(result> numeric_limits<int>::max()){
                    return str[0]=='-'?numeric_limits<int>::min():numeric_limits<int>::max();
                }
            }
            return str[0]=='-'?-result:result;
        }
    };
    
  • 相关阅读:
    jQuery
    jquery操作滚动条滚动到指定元素位置 scrollTop
    javascript的offset、client、scroll使用方法
    js javascript:void(0) 真正含义
    Js中数组Array的用法
    javascript中typeof、undefined 和 null
    函数的参数是函数,函数中Ajax返回的回调函数中的函数运行
    xampp中php手动升级
    jQuery Mobile里xxx怎么用呀? (事件篇)
    eval解析JSON中的注意点
  • 原文地址:https://www.cnblogs.com/ysherlock/p/9687100.html
Copyright © 2011-2022 走看看