[InterviewBit] Atoi

Atoi

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
int Solution::atoi(const string A) {
long long res = 0;
long long sign = 1;
if(A[0] == '-') sign = -1;
for(int i = sign == -1 ? 1 : A[0] == '+' ? 1 : 0; i < A.length() and isdigit(A[i]); i++) {
res = res * 10 + A[i] - '0';
if(sign * res < INT_MIN) return INT_MIN;
if(sign * res > INT_MAX) return INT_MAX;
}
return sign * res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/28/PS/interviewbit/atoi/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.