LeetCode OJ刷题历程——Sting to Integer(atoi)
2016-03-06 13:59
197 查看
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.Requirements for atoi:The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
以上是题目要求。
本题也较为简单,需要注意的,如题所说,注意考虑所有可能的输入,下面贴出代码:
class Solution { public: int myAtoi(string str) { vector<int> p; bool positive_sign = true; long long int sum = 0; bool first = true; for(size_t i = 0;i<str.size();i++){ if(first){ if(str[i] == '-' || (str[i] <='9' && str[i] >='0') || str[i] == '+'){ first = false; if(str[i] == '-'){ positive_sign = false; continue; } else if(str[i] == '+') continue; }else if(str[i] != ' ') return 0; }if(!first){ if(str[i] <='9' && str[i] >='0'){ p.push_back(str[i] - '0'); //j++; } else break; } } if((p.size()>10)) if(positive_sign) return 2147483647; else return -2147483648; else{ for(int i = 0;i<p.size();i++){ sum = sum*10 +p[i]; } if((sum>>31)>0) if(positive_sign) return 2147483647; else return -2147483648; else return positive_sign?sum:-sum; } } };最需要注意的是,如何判断转换后的数超出界限问题,有可能超出long long int.......
相关文章推荐
- 2、JS中的表达式和运算符
- 20145222黄亚奇《Java程序设计》第1周学习总结
- 转载:C# 之泛型详解
- 面向对象 小游戏 打飞机
- 安装node.js,解决ionic安装
- 微信JSSDK多图片上传并且解决IOS系统上传一直加载的问题
- org.xml.sax.SAXParseException的错误解决
- mysql 不同步
- [LeetCode]28 实现子字符串匹配
- JS判断是否是移动设备进行http链接重定向
- 软件测试学习(2)
- HDU 2516 取石子游戏 [斐波那契博弈]
- [LeetCode]137. Single Number II
- 杭电1250
- 004.unity相机
- nginx配置里的fastcgi_index是用来干嘛?和index的区别是?
- [BZOJ3991] [SDOI2015]寻宝游戏
- <android编译ffmpeg+x264+faac> <Android/NDK环境下FFmpeg及AAC,MP3,X264的编译>
- Ubuntu14.04下,GO语言的安装!
- hdu 5120 Intersection(求相交环面积)