题意:将字符串转化成数字。
前置有空格,同时有正负号,数字有可能会溢出,这里用long long解决(leetcode用的是g++编译器),这题还是很有难度的。
1 class Solution { 2 public: 3 int myAtoi(string str) { 4 int sign = 1,i = 0; 5 for(;i<str.size() && str[i] == ' '; ++i); 6 char ss[3] ="+-" ; 7 int sn[3] ={1,-1}; 8 for(int j =0;j<2;++j){ 9 if(str[i] == ss[j]) { 10 sign *= sn[j]; 11 i++; 12 break; 13 } 14 } 15 16 long long ans = 0; 17 for (; i<str.size(); ++i) 18 { 19 if(isdigit(str[i])){ 20 ans = 10*ans + str[i] - '0'; 21 if(sign == 1 && ans > (long long)INT_MAX){ 22 ans = (long long)INT_MAX;break; 23 } 24 else if(sign == -1 && ans> -(long long)INT_MIN){ 25 ans = -(long long)INT_MIN;break; 26 } 27 } 28 else break; 29 } 30 return ans * sign; 31 } 32 };