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

    8. String to Integer (atoi)

     
     
    Total Accepted: 97070 Total Submissions: 721266 Difficulty: Easy

    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.

    Update (2015-02-10):
    The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

    Code:

    int myAtoi(char* str) {
        if(!str)
            return 0;
        int sign = 1;
        int num = 0;
        while(*str == ' ')
            str++;
        if(*str == '+')
            str++;
        else if(*str == '-')
        {
            sign = -1;
            str++;
        }
        while(*str!='')
        {
            if(*str == '+'||*str == '-')
                return 0;
            else if(*str<'0'||*str>'9')
                return num*sign;  
            if (num > INT_MAX / 10)   
                    return sign == 1? INT_MAX : INT_MIN;  
                num*=10;
            if ((*str - '0') > (INT_MAX - num))   
                    return sign == 1? INT_MAX : INT_MIN;   
            num = num + *str - '0';  
            str++;
        }
        return num*sign;
    }

  • 相关阅读:
    Linux shell 获取当前时间之前N天
    python 连接oracle 数据库
    Python 连接mysql
    python字符串反转
    java基础之数据类型转换
    java 基础之数据类型
    使用sublime编辑器编辑eclpse跑tomcat的项目不及时更新问题的解决方法
    日常git命令
    快速排序,按某个属性,或按“获取排序依据的函数”,来排序
    Gulp初识
  • 原文地址:https://www.cnblogs.com/Alex0111/p/5382991.html
Copyright © 2011-2022 走看看