leetcode中字符串转换为整数
来源:互联网 发布:创始于淘宝的女装品牌 编辑:程序博客网 时间:2024/06/14 00:37
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.
这里面最关键的是对溢出的处理,C中32位int型的范围是-2147483648到2147483647。
如果n>INT_MAX,则说明最后一步进行10*n转换时n>INT_MAX,所以当得知n>INT_MAX时,直接返回INT_MAX。
如果n==INT_MAX/10,则比较最后一个数字与INT_MAX%10即7的大小,如果比7大,则返回INT_MAX。
int myAtoi(char* str) { if(str == NULL) return 0; int i = 0; int sign = 1; int n = 0; while(isspace(*str))//跳过空格 str++; if(str[0] == '-') { sign = -1; i++; } else if(str[0] == '+') { i++; } while(isdigit(str[i])) { if(n > INT_MAX/10||((n ==INT_MAX/10) && (str[i]-'0')>7)) { if(sign==1) return INT_MAX; else return INT_MIN; } n = 10 * n + (str[i++] - '0'); } return sign * n;}
阅读全文
1 0
- leetcode中字符串转换为整数
- MFC 中 CString 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 字符串转换为整数
- 整数转换为字符串
- 字符串转换为整数
- 字符串转换为整数
- 整数转换为字符串
- 字符串转换为整数
- 字符串转换为整数
- VS2013 密钥
- Leetcode 76. Minimum Window Substring
- 小白浅谈Linux
- MySQL外连接
- MapReduce 类的封装思想
- leetcode中字符串转换为整数
- JQUERY实现列表检索功能
- Retrofit 2.0 使用总结
- MySQL复合条件连接查询
- java反射
- 算法笔记(3) 学习技巧
- java标识符命名规则
- 通过远程jdbc方式连接到hive数据仓库
- 最长不下降子序列【ccf中学计算机程序设计 基础篇】