Skip to content

Commit

Permalink
Create String to Integer (atoi).cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
Ayu-99 authored Jan 14, 2022
1 parent 2e77e6b commit bb969c7
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Leetcode Challenge/January/String to Integer (atoi).cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Solution {
public :
int myAtoi(string s) {
if(s.length()==0) return 0;

int i=0;
while(i<s.size() && s[i]== ' ') {
i++;
}
s = s.substr(i); //i ---> last of string

int sign = +1;
long ans = 0;

if(s[0] == '-') sign = -1;

int MAX = INT_MAX, MIN = INT_MIN;
i = (s[0] == '+' || s[0] == '-') ? 1 : 0;

while(i < s.length()) {
if(s[0] == ' ' || !isdigit(s[i])) break;

ans = ans * 10 + s[i]-'0';
if(sign == -1 && -1*ans < MIN) return MIN;
if(sign == 1 && ans > MAX) return MAX;

i++;
}q

return (int)(sign*ans);
}
};

0 comments on commit bb969c7

Please sign in to comment.