leetcode---String to Integer (atoi)
2016-04-02 17:42
423 查看
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.
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.
class Solution { public: bool isNum(char a) { if(a < '0' || a > '9') return false; return true; } int myAtoi(string str) { int result = 0; int len = str.length(); int flag; int i = 0; while(str[i] == ' ') //去掉前面的空格 i++; if((str[i] == '+' || str[i] == '-') && (str[i+1] == '+' || str[i+1] == '-')) { return 0; } else if(str[i] == '-') { flag = -1; i++; } else if(str[i] == '+') { flag = 1; i++; } else { flag = 1; } while(str[i] == '0') //去掉前面的0 i++; int j = i; for(; i<len; i++) { if(!isNum(str[i])) break; result = result * 10 + str[i] - '0'; if(i-j >= 10 || result < 0) //溢出 if(flag > 0) return pow(2,31) - 1; else return pow(2, 31) * (-1); } return result * flag; } };
相关文章推荐
- 可视化深度学习和人类感知Visualizing Representations: Deep Learning and Human Beings-3
- 《图解HTTP》
- GDB 进行调试 使用心得
- spoj ONP - Transform the Expression 中缀转后缀
- 清明前夕知名圈子人李帅回家祭祖,言“根”话题
- hdoj Simply Syntax 1433 (模拟)
- 20145311 《Java程序设计》第5周学习总结
- Log4j的使用
- IOS学习之——通讯录的应用
- ToString()的各种用法(大全)
- Sublime Text3安装 + 破解码(最新) + 插件
- Android学习之Design Support Library中TextInputLayout的使用
- 【计导作业】文件——过滤注释
- Git忽略规则及.gitignore规则不生效的解决办法
- Java 实现从数组删除指定位置元素
- 使用 rplidar测试hector_mapping
- 编程之美2.14 求数组的子数组之和的最大值
- POJ2728 Desert King
- 额外红包 编辑功能 插入数据
- 虚拟机的安装