leetcode | String to Integer (atoi)

来源:互联网 发布:linux如何强制退出 编辑:程序博客网 时间:2024/06/10 05:39

String to Integer (atoi) : https://leetcode.com/problems/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.

Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


解析

本题难点在于各种特殊情况的处理:
各种输入特例
“+0”, “-0”, “0”, 都应返回 0
“ +123”,”+123”, “123” ,”123ab123” 都应返回123
“-123”,返回 -123
“”, “+”, “-“, “abc”,”+-1”,”~2”,等 应返回0
以及溢出
“2147483648“返回 INT_MAX (2147483647)
“-21474836480”返回 INT_MIN (-2147483648)

需要注意的是,如何区分正确的0和错误字符返回的0
定义一个全局变量,用来标记错误的0

int g_error = 0;int myAtoi(char* strl) {    if (strl == NULL) {        g_error = -1;        return 0;    }    // 跳过空格    while (*strl != '\0' && *strl == ' ') {            strl++;    }    int sign = 0; // 符号位,负数为1,正数为0    if ((strl[0] == '+' || strl[0] == '-') && strl[1] == '\0') {        g_error = -2;        return 0;    } else if (strl[0] == '+') {        sign = 0;        strl++;    } else if (strl[0] == '-') {        sign = 1;        strl++;    }    long result = 0;    for (; *strl != '\0'; strl++) {        int num = *strl- '0';        if (num < 0 || num > 9) {            break;        } else {            result = result*10 + num;            // 处理溢出            if (sign && (result > INT_MAX)) {                g_error = -3;                return INT_MIN;            }            if (!sign && (result > INT_MAX)) {                g_error = -3;                return INT_MAX;            }        }    }    return sign ? -result : result;}

上述程序虽然通过 leetcode 的OJ,但是没有很好的解决溢出问题,上文中的算法是用 long 表示结果。
以下方法参考,http://blog.csdn.net/v_july_v/article/details/9024123

bool isSpace(const char ch) {    if (ch == ' ' || ch == '\n' ||  ch == '\t' ||  ch == '\b' ||  ch == '\r' ||  ch == '\f')        return true;    return false;}bool isDigit(const char ch) {    if (ch < '0' || ch > '9')        return false;    return true;}int MyAtoi(const char* str) {    if (str == NULL || *str == '\0')        return 0;    static const int MAX = (int) ((unsigned int) ~0 >> 1);    static const int MIN = -(int)((unsigned int) ~0 >> 1) - 1;    static const int MAX_DIV = MAX / 10;    static const int MAX_RES = MAX % 10;    static const int MIN_DIV = MIN / 10;    static const int MIN_RES = MIN % 10;    bool minus = false;    int num = 0; // 最终结果    while (isSpace(*str)) {        str++;    }    if (*str == '+' || *str == '-') {        if (*str == '-')            minus = true;        str++;    }    while (isDigit(*str)) {        int c = *str - '0';// 当前数字        // 首先判断 10*num 是否会溢出,然后判断 10*num + c 是否会溢出        if (!minus && (num > MAX_DIV || (num == MAX_DIV && c > MAX_RES))) {            return MAX;        }        if (minus && (num < MIN_DIV || (num == MIN_DIV && c < MIN_RES))) {            return MIN;        }        num = num*10 + c;        str++;    }    return minus ? -num : num;}
0 0
原创粉丝点击