zoukankan      html  css  js  c++  java
  • String to Integer (atoi)

    Implement atoi to convert a string to an integer.

    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    class Solution {
    public:
        int atoi(string str) {
            long long result=0;
            int flag=1;
            int i=0;
            while(str[i]==' '&&str[i]!=''){
                i++;
            }
            if(str[i]=='-'&&str[i]!=''){
                flag=0;
                i++;
            }else if(str[i]=='+'&&str[i]!=''){
                i++;
            }
            for(;str[i]!='';i++){
                if(str[i]>='0'&&str[i]<='9'){
                    
                    
                    if(flag){
                        result=result*10+str[i]-'0';
                        if(result>0x7FFFFFFF)
                        return 0x7FFFFFFF;
                    }else{
                        result=result*10-(str[i]-'0');
                        if(result<(signed int)0x80000000)
                        return 0x80000000;
                    } 
                }else break;
            }
            return (int)result;
            
            
        }
    };
    

     注意:

    1、字符前的空格处理;

    2、无效字符输入

    3、整数越界问题,此处使用了小技巧,将返回类型定义为long long。再分开判断是否越界

    32位整数范围((signed int) 0x80000000~0x7FFFFFFF) 

  • 相关阅读:
    Tomcat压缩传输设置
    Spring事务的开启方式
    Transactional参数说明
    Java获取异常堆栈信息
    ElasticSearch的matchQuery与termQuery区别
    156-PHP strrpos和strripos函数
    155-PHP stripos函数
    154-PHP strpos函数
    153-PHP htmlentities函数
    152-PHP htmlspecialchars函数
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4394163.html
Copyright © 2011-2022 走看看