此题不难,主要在于你能否考虑到多种细节情况,下面总结如下
1.有空格 " 134 45"
2.有符号 " + 23 4" "- 234"
3.有其他字符 "af+234"
4.超出临界值 "9223372036854775809"
代码如下:
1 public static int atoi(String str) { 2 3 if (str == null || str.trim().length() == 0) { 4 return 0; 5 } 6 int i = 0; 7 8 // 去空格 9 str = str.trim(); 10 // 符号 11 char flag = '+'; 12 if (str.charAt(0) == '-') { 13 flag = '-'; 14 i++; 15 } else if (str.charAt(0) == '+') { 16 flag = '+'; 17 i++; 18 } else if (str.charAt(0) >= '0' && str.charAt(0) <= '9') { 19 flag = '+'; 20 } else { 21 return 0; 22 } 23 24 // 计算 25 double result = 0; 26 while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') { 27 result = result * 10 + (str.charAt(i) - '0'); 28 i++; 29 } 30 31 if (flag == '-') { 32 result = -result; 33 } 34 35 if (result > Integer.MAX_VALUE) { 36 result = Integer.MAX_VALUE; 37 } 38 if (result < Integer.MIN_VALUE) { 39 result = Integer.MIN_VALUE; 40 } 41 42 return (int) result; 43 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步