JuniorCodeCommonNot answered yet
Implement int atoi(const char* str)
Implement myAtoi: convert a C-string to an int, mimicking the standard atoi.
Requirements:
- Skip leading spaces, then handle an optional
+/-sign. - Accumulate digits until the first non-digit character, where you stop.
- Clamp the result to
INT_MIN/INT_MAXon overflow. - Return 0 for a null or empty input.
- Do not use
std::stoi,strtol, orstd::from_chars.
int myAtoi(const char* s) {
// your code here
}
Write the implementation.
Skip leading whitespace, handle optional sign, then accumulate digits: result = result * 10 + digit. Handle overflow (clamp to INT_MIN/INT_MAX per the standard) and stop at the first non-digit character.
- ✗Not handling leading whitespace (the standard
atoiskips it) - ✗Integer overflow during accumulation — check before multiplying
- ✗Not handling the negative sign correctly: '-' before digits sets a flag
- →What is the difference between
atoi,strtol,std::stoi, andstd::from_chars? - →How does
std::from_charsdiffer fromstd::stoiin terms of error handling?
Contents
Task
Implement int myAtoi(const char* str) equivalent to the standard atoi, handling whitespace, sign, and overflow.
Solution
int myAtoi(const char* s) {
if (!s) return 0;
while (*s == ' ') ++s;
int sign = 1;
if (*s == '-' || *s == '+') { if (*s == '-') sign = -1; ++s; }
long long result = 0;
while (std::isdigit(*s)) {
result = result * 10 + (*s++ - '0');
if (result * sign > INT_MAX) return INT_MAX;
if (result * sign < INT_MIN) return INT_MIN;
}
return static_cast<int>(result * sign);
}
Key points
- Use
long longfor intermediate result to detect overflow before truncating. - Stop at first non-digit — standard
atoibehaviour. - For production code, prefer
std::from_chars(C++17): no allocation, explicit error reporting.
Contents