面试题67. 把字符串转换成整数
根据题意,有以下四种字符需要考虑:
数字越界处理:题目要求返回的数值范围应在 [−231,231−1],因此需要考虑数字越界问题。而由于题目指出 环境只能存储 32 位大小的有符号整数 ,因此判断数字越界时,要始终保持res在 int 类型的取值范围内。
package String;import org.junit.Test;/*** @Classname String.JZ67把字符转为整数* @Description TODO* @Date 2023/3/8 21:45* @Created by xjl*/
public class JZ67把字符转为整数 {public int strToInt(String str) {char[] c = str.trim().toCharArray();if (c.length == 0) {return 0;}int res = 0, bndry = Integer.MAX_VALUE / 10;int i = 0, sign = 1;if (c[0] == '-') {sign = -1;i++;} else if (c[0] == '+') {i++;}for (int j = i; j < c.length; j++) {if (c[j] < '0' || c[j] > '9') {break;}if (res > bndry || res == bndry && c[j] > '7') {return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;}res = res * 10 + (c[j] - '0');}return sign * res;}@Testpublic void test(){int i = strToInt(" -42");System.out.println(i);}
}
复杂度分析:
《leetcode》
上一篇:SOA架构的理解
下一篇:【Unity】多分辨率适配