Skip to content

Commit

Permalink
Merge pull request #911 from AkshatAggarwal14/Issue#906
Browse files Browse the repository at this point in the history
8. | String to Integer (atoi) | C++
  • Loading branch information
noisefilter19 authored Oct 1, 2021
2 parents c64ec6d + 7bf149c commit 57d30bf
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions C++/String_to_integer_atoi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// https://leetcode.com/problems/string-to-integer-atoi/
class Solution {
public:
int myAtoi(string str) {
int sign = 1, i = 0;
while (str[i] == ' ') i++;
if (str[i] == '-' || str[i] == '+') sign = 1 - 2 * (str[i] == '-'), i++;
long long int base = 0;
while (str[i] >= '0' && str[i] <= '9') {
base = 10 * base + (str[i++] - '0');
if (base > INT_MAX) {
if (sign == -1) return INT_MIN;
return INT_MAX;
}
}
if (base > INT_MAX) {
if (sign == -1)
return INT_MIN;
else
return INT_MAX;
}
return (int)base * sign;
}
};

0 comments on commit 57d30bf

Please sign in to comment.