Skip to content

Commit

Permalink
Solve: 8. String to Integer (atoi).cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
fkdl0048 committed Sep 27, 2024
1 parent 9f9d5f7 commit 226d9ca
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
3 changes: 2 additions & 1 deletion 2024/LeetCode/7. ReverseInteger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ class Solution {

return ans;
}
};
};

36 changes: 36 additions & 0 deletions 2024/LeetCode/8. String to Integer (atoi).cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution {
public:
int myAtoi(string s) {
int i = 0;
long ans = 0;
int sign = 1;

while(i < s.length() && s[i] == ' ' )
i++;

if (s[i] == '-')
{
i++;
sign = -1;
}
else if (s[i] == '+')
i++;

while(i < s.length())
{
if (s[i] >= '0' && s[i] <= '9')
{
ans = ans * 10 + (s[i] - '0');
if (ans > INT_MAX && sign == -1)
return INT_MIN;
else if (ans > INT_MAX && sign == 1)
return INT_MAX;
i++;
}
else
return ans * sign;
}

return (ans * sign);
}
};

0 comments on commit 226d9ca

Please sign in to comment.