8. String to Integer (atoi)
C++ | 100% Success | Brute Force | Easy Understandingclass Solution {
public:
int myAtoi(string s) {
int sign = 1;
int i = 0;
long long int ans = 0;
while(s[i]==' ')i++;
if(s[i]=='-'){
sign = -1;
i++;
}
else if(s[i]=='+') i++;
int u = INT_MAX;
int l = INT_MIN;
int j = i;
while(s[j]>='0' && s[j]<='9'){
if(s[j]==' ') continue;
ans += s[j] - '0';
if(sign*ans<=l)return l;
else if(sign*ans>=u) return u;
ans = ans * 10;
j++;
}
ans = ans /10;
ans = ans*sign;
return (int)ans;
}
};
Comments
Post a Comment