From 1f302816aca9361e5300de2eeeb335915a009afb Mon Sep 17 00:00:00 2001 From: CyC2018 Date: Fri, 30 Oct 2026 20:18:08 +0800 Subject: [PATCH] =?UTF-8?q?Update=2067.=20=E6=8A=8A=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E8=BD=AC=E6=8D=A2=E6=88=90=E6=95=B4=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新题目描述与输入输出示例,补充基于 atoi 规则的处理流程及溢出边界判断说明。 --- notes/67. 把字符串转换成整数.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) 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)