String to Integer (atoi) LeetCode 解题报告
来源:互联网 发布:php有必要培训吗 编辑:程序博客网 时间:2024/06/10 03:01
题目
就是把输入的字符串转为整数,具体要求如下:
1、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.
译:(这个函数最开始丢弃空白字符知道第一个不空白字符的字符出现,然后从这个字符开始,接受一个可选的正号或负号,随后是尽可能多的数字,然后将它们解释为数值)。
2、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.
译:(这个字符串可以包含那些形成整数的额外字符,这些字符将被忽略,对这个函数的将不起作用)。[这句翻译我也有点迷糊,有更好的翻译希望留言讨论]
3、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.
译:(如果这个开始的为非空白字符不是合法的整数,或者是这个字符序列不存在因为它要么是空的要么是纯空白字符,不会发生转换)。
4、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.
译:(如果没有发生合法的转换,返回0. r如果这个正确值超出可表达的范围,返回整数的最大值(2147483647)或最小值(-2147483648))。
思路
题目细节较多,具体的要求在上面四点中,难度在于各种情况考虑周全。
代码
public int myAtoi(String str) { int i = 0,res = 0,sign = 0,len = str.length()-1; while(i <= len && str.charAt(i) == ' ') i++; if(i <= len && (str.charAt(i) == '-' || str.charAt(i) == '+')){ if(str.charAt(i) == '-'){ sign = -1; } i++; } while(i <= len && str.charAt(i) >= '0' && str.charAt(i) <= '9'){ if(res > Integer.MAX_VALUE / 10 || ((res == Integer.MAX_VALUE / 10) && str.charAt(i)-'0' > 7)){ if(sign == 1){ return Integer.MAX_VALUE; }else{ return Integer.MIN_VALUE; } } res = res*10 + str.charAt(i++)-'0'; } return res*sign; }
- 【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] 8. String to Integer (atoi) 解题报告
- [Leetcode] 8. String to Integer (atoi) 解题报告
- leetcode解题报告8. String to Integer (atoi)
- [LeetCode 解题报告]008.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:String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- LeetCode String to Integer(atoi)
- LeetCode :String to Integer (atoi)
- C语言内存知识补充
- 贪心算法——C++实现经典案例——中级
- python爬虫学习第二十四天
- JavaScript学习之用数组实现图片轮播
- list集合迭代过程中增删出现异常,及解决方法
- String to Integer (atoi) LeetCode 解题报告
- VBA学习1_教你快速入门Excel-宏与VBA(上)
- 数据结构-线性表
- mac 中的 protobuf 安装编译 Java
- 秒杀系统
- 归并求逆序对
- HDU
- 1288 汽油补给(贪心+单调栈)
- MYSQL 最近知识总结(2)