https://leetcode.com/problems/string-to-integer-atoi/
Title: Converts a string to an integer.
Rules:
1. You can have more than one space before entering a string;
2. Encounters '-' or ' + ' or numeric characters starting with multiple numeric characters consecutively. That is encountered other characters end;
3. Multiple consecutive numeric characters may be followed by other characters, but not integers;
4. When the input is empty, or is a string that cannot be converted, output 0;
5. When the integer is greater than 2147483647, the output is 2147483647. When less than-2147483648, then output-2147483648
Idea: The main is to pay attention to overflow situation, in the process of traversal to determine whether overflow, or the final result can be more than 64 bits.
1 classSolution {2 Public:3 intMyatoi (stringstr) {4 intI=0, len=str.length ();5 if(len==0)6 return 0;7 intflag=0;8 while(i<len&&str[i]==' '){9i++;Ten } One if(str[i]=='-') A { -flag=1; -i++; the } - Else if(str[i]=='+') - { -i++; + } - Else if(str[i]<'0'|| Str[i]>'9') + { A return 0; at } - Long Longsum=0; - while(i<Len) { - if(str[i]>='0'&&str[i]<='9') - { -sum=sum*Ten+ (str[i]-'0'); in if(sum>2147483647) - Break; to } + Else - Break; thei++; * } $ intresult=sum;Panax Notoginseng if(sum>2147483647){ - if(flag) the return-2147483648; + Else A return 2147483647; the } + Else - { $ if(flag) $ return-result; - Else - returnresult; the } - }Wuyi};
Leetcode 8. String to Integer (atoi)