diff --git a/notes/67. 把字符串转换成整数.md b/notes/67. 把字符串转换成整数.md index bcb2f9de..f829de85 100644 --- a/notes/67. 把字符串转换成整数.md +++ b/notes/67. 把字符串转换成整数.md @@ -6,20 +6,26 @@ ## 题目描述 -将一个字符串转换成一个整数,字符串不是一个合法的数值则返回 0,要求不能使用字符串转换整数的库函数。 +实现 atoi,将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数:跳过开头的空格,读入可选的正负号,再读入尽可能多的数字,遇到非数字字符就停止;没有读到数字时返回 0,超出 int 范围时返回 Integer.MAX_VALUE 或 Integer.MIN_VALUE。牛客的版本要求整个字符串都是合法数值,否则返回 0。 ```text Input: -+2147483647 -1a33 +" -42" +"4193 with words" +"words and 987" +"-91283472332" Output: -2147483647 +-42 +4193 0 +-2147483648 ``` ## 解题思路 +按上面的规则逐个字符处理,难点在于判断溢出。溢出要在乘 10 之前判断:border = Integer.MAX_VALUE / 10 = 214748364,ret 大于 border,或者等于 border 且下一位大于 7 时,ret × 10 加上下一位会超过 2147483647,直接返回边界值。负数的下界 -2147483648 末位是 8,也走这个分支,返回 Integer.MIN_VALUE,结果正确。 + ```java public int myAtoi(String str) { if (str == null || str.length() == 0)