Leetcode-8. String to Integer (atoi)

xiaoxiao2021-02-28  38

8. 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 myAtoi(string str) { int sign = 1, base = 0, i = 0; while (str[i] == ' ') { i++; } if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-'); } while (str[i] >= '0' && str[i] <= '9') { if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) { if (sign == 1) return INT_MAX; else return INT_MIN; } base = 10 * base + (str[i++] - '0'); } return base * sign; } };
转载请注明原文地址: https://www.6miu.com/read-250086.html

最新回复(0)