Leetcode 8. String to Integer (atoi)
Posted Deribs4
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 8. String to Integer (atoi)相关的知识,希望对你有一定的参考价值。
8. String to Integer (atoi)
- Total Accepted: 120050
- Total Submissions: 873139
- Difficulty: Easy
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 possibe input cases.
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.
思路:仿写将字符串转换为数字的转换函数。注意以下4种情况:
1. 空串
2. 只包含空格的串
3. 字符串去除前缀空格以后,剩下字符串的第一序列不是数字。比如字符串“ -asd123”,去掉前缀空格以后是“-asd123”,剩下字符串的第一序列不是数字。
4. 不满足以上3条,但转换后的数字超出整数范围。
代码:
1 class Solution { 2 public: 3 int myAtoi(string str) { 4 int i = 0, sign = 1, sum = 0; 5 str = str + "end"; 6 while(str[i] == ‘ ‘) i++; 7 if (str[i] == ‘-‘ || str[i] == ‘+‘){ 8 sign = (str[i] == ‘-‘)?-1:1; 9 i++; 10 }else{ 11 sign = 1; 12 } 13 while (str[i] >= ‘0‘ && str[i] <= ‘9‘) { 14 if (sum > INT_MAX/10 || (sum == INT_MAX/10 && str[i] - ‘0‘>7)){ 15 if (sign == 1) return INT_MAX; 16 return INT_MIN; 17 } 18 sum *= 10; 19 sum += str[i++] - ‘0‘; 20 } 21 return sum*sign; 22 } 23 };
以上是关于Leetcode 8. String to Integer (atoi)的主要内容,如果未能解决你的问题,请参考以下文章
leetcode:String to Integer (atoi)
8. 字符串转整数(实现atoi函数) [leetcode 8: String to Integer (atoi)]
8. 字符串转整数(实现atoi函数) [leetcode 8: String to Integer (atoi)]
leetcode-8. String to Integer (atoi)