LeetCode OJ8 String to Integer (atoi) 小结
2015-09-23 10:20
381 查看
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. Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
解题思路
这道题目的处理思路主要是, 提取字符串中的 首个’-‘, ‘+’ 字符, 以及相应的数字, 并且, 需要考虑溢出的问题my code
class Solution { public: int myAtoi(string str) { int len = str.size(); bool start = false; bool isNeg = false; bool isInValid = false; long convertNum = 0; for (int i = 0; i != len; i++) { if (str[i] == ' ' && start == false) continue; if (str[i] == '+' && start == false) { start = true; continue; } if (str[i] == '-' && start == false) { start = true; isNeg = true; continue; } if (str[i] < '0' || str[i] > '9') { isInValid = true; break; } convertNum = 10 * convertNum + str[i] - '0'; start = true; if (convertNum > INT_MAX) break; } convertNum = isNeg ? -1 * convertNum : convertNum; // overflow detection if (convertNum >= INT_MAX || convertNum <= INT_MIN) convertNum = isNeg ? INT_MIN : INT_MAX; return convertNum; } };
大神的代码
demo1
感觉好像外层的for 没有任何的意义使用find_first_not_of 简化流程
int myAtoi(string str) { long result = 0; int indicator = 1; for(int i = 0; i<str.size();) { i = str.find_first_not_of(' '); if(str[i] == '-' || str[i] == '+') indicator = (str[i++] == '-')? -1 : 1; while('0'<= str[i] && str[i] <= '9') { result = result*10 + (str[i++]-'0'); if(result*indicator >= INT_MAX) return INT_MAX; if(result*indicator <= INT_MIN) return INT_MIN; } return result*indicator; } }
相关文章推荐
- Yoshua Bengio等大神传授:26条深度学习经验
- IAR常用快捷键和使用小技巧
- sublime Text2 必备插件(SASS SCSS)
- Computer Science Conference Rankings
- qt 与mysql建立交互式连接
- Aggregated Counting-----hdu5439(2015 长春网络赛 找规律)
- vim 程序编辑器
- vim使用总结
- mtk移植总结_MTK
- 【干货】微信场景之H5页面制作免费工具大集合
- 反射注入失败的原因!
- 纯CSS实现Tab切换标签效果代码
- Hibernate与Spring的事务管理
- 12.matlab数据的导入和导出,以matlab工作区workspace为source和destination
- JS打开模式对话框
- linux下yum安装配置mysql数据库
- OpenGL: 你不知道的左右手坐标系
- Hibernate与Spring的事务管理
- 日志框架Nlog之将日志输出到控制台
- SQL函数:字符串中提取数字,英文,中文,过滤重复字符(转)