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.
把字符串转化成整数,需要考虑全面(不看spoilers)。几种特殊情况:
1.有或者没有符号位。
2.先有很多空格。(这个有点坑,没想到)
3.字符串中出现非数字字符。(我直接认为输入错误return 0,但这道题是把它看做终止符)
4.转化的整数overflow。(存在long long里,然后看overflow没有。我overflow直接return 0,但这道题是截取最大能表达的数)
PS: 应该尝试用条件表达式简化代码。
自己的AC代码:
1 class Solution { 2 public: 3 int myAtoi(string str) { 4 long long x=0; 5 int i,flag=1,begin=0,n=str.size(); 6 for(i=0;i<n;i++){ 7 if(str[i]!=' ') 8 break; 9 } 10 begin=i; 11 if(str[begin]=='-'||str[begin]=='+'){ 12 if(str[begin]=='-') 13 flag=-1; 14 begin++; 15 } 16 for(i=begin;i<n;i++){ 17 if(isdigit(str[i])==1){ 18 x= 10*x+str[i]-'0'; 19 if(flag==1 && x>INT_MAX) 20 return INT_MAX; 21 else if(flag==-1 && -x<INT_MIN) 22 return INT_MIN; 23 }else 24 break; 25 } 26 x=flag*x; 27 return x; 28 } 29 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· 对象命名为何需要避免'-er'和'-or'后缀
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· SQL Server如何跟踪自动统计信息更新?