leetcode 字符串转换整数 (atoi) 中等

题目稍长,贴个连接:https://leetcode-cn.com/problems/string-to-integer-atoi/
注意正数可能存在前置 +,以及注意溢出即可
class Solution { public: int myAtoi(const string& s) { int i = 0, res = 0; while(s[i] == ' ') ++ i; bool flag = s[i] == '-'; i += (flag || s[i] == '+'); while(i < s.size() && isDigit(s[i])) { if(res > INT_MAX / 10 || (res == INT_MAX / 10 && charToInt(s[i]) >= 7 + flag)) { return flag ? INT_MIN : INT_MAX; } res = res * 10 + charToInt(s[i]); ++ i; } return flag ? -res : res; } bool isDigit(const char &c) { return c >='0' && c <= '9'; } int charToInt(const char &c) { return c - '0'; } };

浙公网安备 33010602011771号