[LeetCode 解题报告]008.String to Integer (atoi)
来源:互联网 发布:node.js高级编程 微盘 编辑:程序博客网 时间:2024/05/29 08:22
Description:
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.
spoilers alert... click to show requirements for atoi.
注意Case点:- 该字符串前边可能有若干空格(用#表示空格)“###010”返回值应为10
- 去除前边的若干个空格之后,需考虑接下来的一个字符是‘+‘还是’-’
- 碰到非数字字符结束
- 转换成数字时候需考虑是否产生越界
class Solution {public: int myAtoi(string str) { if(str.length() == 0) return 0; int i = 0, sign = 1, res = 0; while(isspace(str[i])) i ++; if(str[i] == '+' || str[i] == '-') { if(str[i] == '-') sign = 0; i ++; } str = str.substr(i); for(int j = 0; j < str.length(); j ++) { if(!isdigit(str[j])) { str = str.substr(0, j); break; } } if(str.length() == 0) return 0; for(int i = 0; i < str.length(); i ++) { int c = (str[i] - '0'); if(sign == 1 && (res > INT_MAX / 10 || res == INT_MAX / 10 && c > INT_MAX % 10)) { return INT_MAX; } else if(sign == 0 && (res > INT_MAX / 10) || res == INT_MAX / 10 && c > (INT_MAX % 10 + 1)) { return INT_MIN; } res = res * 10 + c; } return sign > 0 ? res : -res; }};
阅读全文
0 0
- 【LeetCode】String to Integer (atoi) 解题报告
- LeetCode解题报告--String to Integer (atoi)
- LeetCode-String to Integer (atoi) -解题报告
- [LeetCode] String to Integer (atoi) 解题报告
- [LeetCode] String to Integer (atoi) 解题报告
- String to Integer (atoi) LeetCode 解题报告
- [LeetCode 解题报告]008.String to Integer (atoi)
- [leetcode] 8. String to Integer (atoi) 解题报告
- [Leetcode] 8. String to Integer (atoi) 解题报告
- leetcode解题报告8. String to Integer (atoi)
- LeetCode(8) String to Integer (atoi)解题报告
- String to Integer (atoi)解题报告
- 【Leetcode】8.String to Integer (atoi) 解题
- [Leetcode]解题文档-String to Integer (atoi)
- LeetCode 008. String to Integer (atoi)
- 【LeetCode】008.String to Integer (atoi)
- leetcode--008. String to Integer (atoi)
- 【LeetCode】 008. String to Integer (atoi)
- 小小白爬虫入门——selenium模拟登录qq空间
- 原生js封装jquery
- c++学习笔记,面向对象设计模式,装饰者模式
- HeadFirstJava 11异常处理
- 蓝桥杯 摆动序列
- [LeetCode 解题报告]008.String to Integer (atoi)
- Error:Cannot find module 'stylus'
- codevs 1214 线段覆盖(贪心 or dp)
- 1、intellij idea 常用快捷键 加快开发速度
- L
- ACM International Collegiate Programming H.动态规划
- COM内部接口调用方式
- iOS 数组求和的一种简单方法
- 第九讲 整合 Spring MVC+Spring+MyBatis