LeetCode---String to Integer (atoi)
来源:互联网 发布:算法时代 下载 编辑:程序博客网 时间:2024/05/22 08:20
题目大意:给出一个数字表示的字符串将其转化为数字。要求算法能够忽略字符串开头的连续空格,当字符串出现其他字符时将字符串就此截断且返回结果,当数字和大于 MAX_INT时返回MAX_INT当数字和小于MIN_INT时返回MIN_INT。
算法思想:
开始时设置一个当前结果和变量,符号变量,和一个开始标记,然后遍历字符串,忽略开头的连续空格符,如果首次遇到'+','-'则标记符号变量且标记开始变量,如果遇到数字则将其加入结果和中且标记开始变量,其他情况则终止遍历,在字符串遍历的时候时刻判断结果和的上下边界。
代码如下:
class Solution {public: int myAtoi(string str) { long long res=0; if(str.length()==0) return res; int sign=1; bool isStart=false; for(char c:str){ if(c==' '&&!isStart){ continue; } else if(isdigit(c)){ res=res*10+c-'0'; isStart=true; } else if(c=='+'&&!isStart) { isStart=true; } else if(c=='-'&&!isStart){ isStart=true; sign=-1; } else{ break; } if(res>2147483647&&sign==1) { res=2147483647; break;} if(res>2147483648&&sign==-1){ res=2147483648; break;} } return res*sign; }};
0 0
- 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)
- CBitmapButton为按钮加载图片注意事项
- 第17篇 基于Bootstarp 仿京东多条件筛选插件的开发(展示下)
- 队列实现栈
- UI基础__控件布局的几种方法总结
- 一起talk C栗子吧(第六十三回:C语言实例--字符串查找)
- LeetCode---String to Integer (atoi)
- android sqlite cursor 没有返回数据,资源占用问题
- Android之退出应用关闭项目每个Activity的总结
- 佛祖保佑,永不宕机/永无bug
- Content Compression Resistance和Content Hugging
- <2> go -反射-函数map化
- 记一次在Windows上搭建React Native Android环境踩过的坑
- 运行时系统(Runtime System)
- 数据库索引的优点与缺点