【leetcode】8.String to Integer (atoi)
8. String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Tips: 本题要自己实现atoi函数,需要声明的包括:
①.java 字符串或者字符数组结尾处并不包含"\0".
②考虑输入的字符串前面有很多空格。
③考虑'+','_'
④我没通过的case有" -12a42",正确输出为 -12。
"2147483648" 正确输出为 2147483647
package medium; public class L8StringToInteger_atoi { public int myAtoi(String str) { if (str == "") return 0; long num = 0; int minus = 1;// + int i = 0; int len = str.length(); while (i < len) { if (str.charAt(i) == ' ') { i++; }else{
break;
} } if (str != null && i < len) { if (str.charAt(i) == '+') { minus = 1; i++; } else if (str.charAt(i) == '-') { minus = -1; i++; } while (i < len) { System.out.println(i + " " + str.charAt(i)); if (str.charAt(i) >= '0' && str.charAt(i) <= '9') { num = num * 10 + minus * (str.charAt(i) - '0'); if ((minus == 1 && num >= 2147483647) ) { num = 2147483647; break; }if( (minus == -1 && num < -2147483648)){ num=-2147483648; break; } i++; System.out.println(i); } else { break; } } } return (int) num; } public static void main(String[] args) { String str = " -0012a42"; L8StringToInteger_atoi l8 = new L8StringToInteger_atoi(); int num = l8.myAtoi(str); System.out.println(num); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!