Skip to content

Instantly share code, notes, and snippets.

@DragonOsman
Last active February 19, 2022 22:32
Show Gist options
  • Save DragonOsman/49e890176d471c19847ed7ed1a9eaafa to your computer and use it in GitHub Desktop.
Save DragonOsman/49e890176d471c19847ed7ed1a9eaafa to your computer and use it in GitHub Desktop.
#include <cctype>
#include <string>
#include <limits>
class Solution {
public:
int myAtoi(string s) {
char sign{};
constexpr int high{ std::numeric_limits<int>::max() };
constexpr int low{ std::numeric_limits<int>::min() };
std::size_t index{};
if (!isdigit(s[0]) && s[0] != '+' && s[0] != '-')
{
do
{
if (!isspace(s[index]) && s[index] != '+' && s[index] != '-')
{
return 0;
}
++index;
} while (!isdigit(s[index]) && s[index] != '+' && s[index] != '-');
}
if ((s[index] == '+' || s[index] == '-') && (index + 1) < s.length())
{
if (s[index + 1] == '-' || s[index + 1] == '+')
{
return 0;
}
else
{
sign = s[index];
++index;
}
}
int value{};
for (std::size_t i{ index }, n{ s.length() }; i < n && isdigit(s[i]); ++i)
{
if (value > (high / 10) || value * 10 > high - (s[i] - '0'))
{
return sign == '-' ? low : high;
}
value = value * 10 + (s[i] - '0');
}
if (sign == '-')
{
value *= -1;
}
return value;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment