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;
    }

  • 相关阅读:
    1084: 计算两点间的距离(多实例测试)
    1083: 数值统计(多实例测试)
    回文数的判断
    1082: 敲7(多实例测试)
    BZOJ 1303 [CQOI2009]中位数图
    计蒜客 Yingchuan Online F题 (Floyd 变形)
    并查集入门题
    常见错点
    单调队列入门题
    线段树入门题
  • 原文地址:https://www.cnblogs.com/Alex0111/p/5382991.html
Copyright © 2011-2022 走看看