lintcode之转换字符串到整数
来源:互联网 发布:洪珮云 知乎 编辑:程序博客网 时间:2024/06/06 03:09
题目:
实现atoi
解答:
此题是细致题,需要考虑到各种情况,比如去除空前缀,去除0前缀,处理非0-9字符,处理小数点等
class Solution {public: /** * @param str: A string * @return An integer */ int atoi(string str) { // write your code here int tag = 1; int len = str.length(); int startPos = 0; while (str[startPos] == '0' || str[startPos] == ' ') { startPos++; } if (str[startPos] == '-') { tag = -1; startPos++; } else if (str[startPos] == '+') { startPos++; } long long LONG = 2147483648; long long int temp = 0; while (startPos <= len) { if (tag == 1 && temp >= INT_MAX) { return INT_MAX; } else if (tag == -1 && temp >= LONG) { return INT_MIN; } else if (str[startPos] == '.') { //由于是转换为int 遇到小数点就可以直接结束了,小数点后面的额是没有意义的 return temp * tag; } else if (startPos < str.length() && !(str[startPos] >= '0' && str[startPos] <= '9')) return temp == 0 ? 0 : tag * temp; else if (startPos < str.length()) { temp = temp * 10 + (str[startPos] - '0'); } startPos++; } return tag * temp; }};
0 0
- lintcode之转换字符串到整数
- lintcode-转换字符串到整数
- lintcode,转换字符串到整数
- Lintcode 转换字符串到整数
- lintcode -- 转换字符串到整数
- LintCode:转换字符串到整数
- lintcode 转换字符串到整数
- 转换字符串到整数——LintCode
- LintCode 54- 转换字符串到整数
- LintCode 54 转换字符串到整数
- [LintCode]54.转换字符串到整数
- LINTCODE——转换字符串到整数
- LintCode-剑指Offer-(54)转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- Miscellaneous | 转换字符串到整数
- leetcode 71. Simplify Path
- minAreaRect-OpenCV
- How to Setup network on centos 7
- WIN8.1 64位 + VS2013 + VTK-5.10.1配置时出现问题
- uml用例图
- lintcode之转换字符串到整数
- POJ2112 Optimal Milking
- 垃圾回收
- Android MD控件之CardView
- 学前端的人为什么也要学习一些后端
- CVE-2014-0160 Heartbleed Bug
- java实现 用数组实现循环队列
- Unity API - B
- 如何打乱100个数呢?