8. String to Integer (atoi)
2016-01-07 10:19
204 查看
题意描述:Implement atoi to convert a string to an integer.
需要注意的情况:
1. 正负号
2. 有效字符之前可能会有空格
3. 有效字符中出现非法字符会截断数字
4. 溢出时输出最大值或最小值
AC代码:
需要注意的情况:
1. 正负号
2. 有效字符之前可能会有空格
3. 有效字符中出现非法字符会截断数字
4. 溢出时输出最大值或最小值
AC代码:
class Solution { public: int myAtoi(string str) { if(str.length() == 0) return 0; int sum = 0; int neg = 1; int loc = 0; while(str[loc] == ' '){ ++ loc; } string new_str = str.substr(loc, (str.length() - loc)); for(int i = 0; i < new_str.length(); ++i){ if(i == 0 && new_str[i] == '-' || i == 0 && new_str[i] == '+'){ if(new_str[i] == '-') neg = -1; }else{ int num = char2num(new_str[i]); if(num != -1){ if(sum > (0x7fffffff / 10) ){ if(neg == -1){ return (int)0x80000000; }else{ return 0x7fffffff; } }else{ sum *= 10; } if(isAddOverflow(sum, num)){ if(neg == -1){ return (int)0x80000000; }else{ return 0x7fffffff; } }else{ sum += num; } }else{ return sum*neg; } } } return neg*sum; } int char2num(char a){ if (a >= '0' && a <= '9'){ return (a - '0'); }else{ return -1; } } int isAddOverflow(int a, int b){ int c = a + b; return ( a > 0 && b > 0 && ( c < a || c < a) || a < 0 && b < 0 && (c > b || c > a)); } };
相关文章推荐
- jQuery常用总结
- Python时间,日期,时间戳之间转换
- 时间服务器
- HAProxy的编译安装配置
- EasyUi心得
- TCP接受和发送程序以及长连接的处理方法
- 将博客搬至CSDN
- cookie显示上次访问时间
- Java 8:如何使用流方式查询数据库?
- 同志们再等等,三四月份跳槽加薪才最多
- android 任务栈启动模式
- 多线程的简单介绍与了解
- C/C++的就业,发展方向
- 把APK安装到SD卡和TF卡实现方案
- css3 transform, transition, animation区别和使用场景
- Understanding Steering Behaviors: Queue
- 邮件开发:复杂邮件的一个示例
- 给初学编程的人的新年干货
- android之VOLD:staging目录作用与ASEC文件 -总结
- weblogic集群搭建、代理服务器