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 don't see below and ask yourself what is 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, the starting from this character, takes a optional initial plus or minus sign followed by as many numerical digits as P Ossible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which is ignored and has no Effe CT on the behavior of this function.
If the first sequence of non-whitespace characters in STR isn't a valid integral number, or if no such sequence exists be Cause 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 Returne D.
Idea: A translation function that translates a string into a number. Be aware of the following 4 scenarios:
1. Empty string
2. Strings that contain only spaces
3. After the string is stripped of the prefix space, the first sequence of the string is not a number. For example, the string "-asd123", minus the prefix space is "-asd123", leaving the first sequence of strings is not a number.
4. The above 3 is not satisfied, but the converted number is outside the integer range.
Code:
1 classSolution {2 Public:3 intMyatoi (stringstr) {4 inti =0, sign =1, sum =0;5str = str +"End";6 while(Str[i] = =' ') i++;7 if(Str[i] = ='-'|| Str[i] = ='+'){8Sign = (Str[i] = ='-')?-1:1;9i++;Ten}Else{ OneSign =1; A } - while(Str[i] >='0'&& Str[i] <='9') { - if(Sum > int_max/Ten|| (Sum = = int_max/Ten&& Str[i]-'0'>7)){ the if(Sign = =1)returnInt_max; - returnint_min; - } -Sum *=Ten; +Sum + = str[i++]-'0'; - } + returnsum*Sign ; A } at};
Leetcode 8. String to Integer (atoi)