diff --git a/notes/67. 把字符串转换成整数.md b/notes/67. 把字符串转换成整数.md index 19fdd290..1841ca63 100644 --- a/notes/67. 把字符串转换成整数.md +++ b/notes/67. 把字符串转换成整数.md @@ -2,7 +2,7 @@ ## 题目链接 -[NowCoder](https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tqId=11202&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) +[Leetcode](https://leetcode.cn/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/) ## 题目描述 @@ -21,19 +21,33 @@ Output: ## 解题思路 ```java -public int StrToInt(String str) { +public int myAtoi(String str) { if (str == null || str.length() == 0) return 0; - boolean isNegative = str.charAt(0) == '-'; - int ret = 0; - for (int i = 0; i < str.length(); i++) { - char c = str.charAt(i); - if (i == 0 && (c == '+' || c == '-')) /* 符号判定 */ - continue; - if (c < '0' || c > '9') /* 非法输入 */ - return 0; - ret = ret * 10 + (c - '0'); + int i = 0, n = str.length(); + while (i < n && str.charAt(i) == ' ') { + i++; } - return isNegative ? -ret : ret; + if (i == n) + return 0; + int sign = 1; + char c = str.charAt(i); + if (c == '+' || c == '-') { + sign = c == '-' ? -1 : 1; + i++; + } + int ret = 0; + int border = Integer.MAX_VALUE / 10; + while (i < n) { + c = str.charAt(i); + if (c < '0' || c > '9') + break; + if (ret > border || (ret == border && c > '7')) { + return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; + } + ret = ret * 10 + (c - '0'); + i++; + } + return sign * ret; } ```