carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode8:字符串转换整数 (atoi) #59

Open carloscn opened 2 years ago

carloscn commented 2 years ago

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。

函数 myAtoi(string s) 的算法如下:

注意:

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/string-to-integer-atoi

carloscn commented 2 years ago

题目分析:

这道题是中等的原因是因为有各种各样丰富的case需要考虑,我觉得没有太多的必要。

#define NUM_MAX ((char)'9')
#define NUM_MIN ((char)'0')
#define NUM_INT_MAX (2147483647)
#define NUM_INT_MAX_COUNT (10)

static int32_t myatoi(const char *str, int32_t *out)
{
    int32_t ret = 0;
    int32_t val = 0;
    int32_t u = 1;
    int32_t overflow_count = 0;

    UTILS_CHECK_PTR(str);
    UTILS_CHECK_PTR(out);

    if (0 == strlen(str))
        goto finish;

    do {
        if (' ' == *str) {
            continue;
        }
        if ('+' == *str) {
            u = 1;
            continue;
        }
        if ('-' == *str) {
            u = -1;
            continue;
        }
        if ((NUM_MAX < *str) ||
            (NUM_MIN > *str)) {
            break;
        }
        if (overflow_count < NUM_INT_MAX_COUNT)
            val = val * 10 + *str - NUM_MIN;
    } while (*(++str) != '\0' && (++overflow_count < NUM_INT_MAX_COUNT));

    *out = val * u;
finish:
    return ret;
}
carloscn commented 2 years ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/str/12_myatoi_8.c

result:

image