【leetcode】String to Integer (atoi)
来源:互联网 发布:怎么查网络ip地址 编辑:程序博客网 时间:2024/05/20 07:36
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.
解题思路:
本题的算法不难,不过通过率比较低,交了很多次才实现出来,因为要考虑很多方面,+-号,溢出,空格输入等,一开始没有完全考虑到这些因素。
代码:
int myAtoi(string str) {
long long int sum=0;//使用long long int型记录sum。
int f1=1,i=0,min=-2147483648,max=2147483647;
while(str[i]==' '&&str[i]!='\0')i++;//清除输入字符串前面的空格输入
if(str[i]=='-')
{
f1=-f1;//用f1标记正负性
i++;
}
else if(str[i]=='+')
{
i++;
}
for(i;i<str.size();i++)
{
if(str[i]>'9'||str[i]<'0')//判断合法性
return sum;
if(f1==1)
{
sum*=10;
sum+=str[i]-'0';
if(sum>=2147483647)//判断是否溢出
return max;
else
continue;
}
else
{
sum*=10;
sum-=str[i]-'0';
if(sum<=-2147483648)
return min;
else
continue;
}
}
return (int)sum;
}
- LeetCode:String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- LeetCode String to Integer(atoi)
- LeetCode :String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- Leetcode : String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- LeetCode-String to Integer (atoi)
- [leetcode] String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- [LeetCode] String to Integer (atoi)
- leetcode String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- 系统新消息
- AndroidStudio 修改 Master Password
- 4、Oracle PL/SQL编译错误查看与处理
- spring 配置文件浅析
- 重写view画圆中间文字
- 【leetcode】String to Integer (atoi)
- js中的包装对象
- 高德地图MapView和其他SurfaceView在同一个Activity中重叠显示透明问题
- 重写ImageView画圆
- Element translate must be declared
- C#控制台基础 检测一个string数组是否包含指定的string字符串
- spring Bean的命名
- C++链表
- Expected resource of type id