LeetCode 8. String to Integer (atoi)
https://leetcode.com/problems/string-to-integer-atoi/
学到了INT_MAX和find_first_not_of(),有意思,不过优化不到8ms,求正解。
class Solution { public: int myAtoi(string str) { long num=0; int f=1; int len=str.length(); int i=str.find_first_not_of(' '); if(str[i]=='-') f=-1,i++; else if(str[i]=='+') i++; for(;i<len&&str[i]>='0'&&str[i]<='9';i++) { num*=10,num+=str[i]-'0'; if(num>=INT_MAX) { if(num*f>=INT_MAX) return INT_MAX; if(num*f<=INT_MIN) return INT_MIN; } } return num*f; } };