1. 64-bit Integer Accumulator
Intuition
Skip whitespace. Check sign. Accumulate digits into a 64-bit long long integer. If the accumulated value with sign exceeds INT_MAX (2147483647), clamp to INT_MAX. If it falls below INT_MIN (-2147483648), clamp to INT_MIN.
When to apply: When 64-bit integers are permitted and simplicity is preferred.
Algorithm
- Initialize
i = 0, sign = 1, total = 0. - While
i < n && s[i] == ' ':i++. - If
i < n && (s[i] == '+' || s[i] == '-'):sign = (s[i] == '-') ? -1 : 1; i++. - While
i < n && isDigit(s[i]): -
total = total * 10 + (s[i] - '0') - If
sign * total > 2147483647: return 2147483647. - If
sign * total < -2147483648: return -2147483648. -
i++. - Return
sign * total.
64-bit Integer Accumulator
2 of 2 questions left todayObservation: String starts immediately with digit '4' (no leading spaces or sign)
Observation: String starts immediately with digit '4' (no leading spaces or sign).
Decision: Sign is +1. Start numerical accumulator: num = 4.
Invariant: Whitespace trimming and sign detection must precede digit parsing.
#include <iostream>#include <string>#include <climits> class Solution {public: int myAtoi(std::string s) { int i = 0, n = s.size(); while (i < n && s[i] == ' ') i++; if (i == n) return 0; int sign = 1; if (s[i] == '+' || s[i] == '-') { sign = (s[i] == '-') ? -1 : 1; i++; } long long total = 0; while (i < n && isdigit(s[i])) { total = total * 10 + (s[i] - '0'); if (sign == 1 && total > INT_MAX) return INT_MAX; if (sign == -1 && -total < INT_MIN) return INT_MIN; i++; } return sign * total; }}; int main() { Solution sol; std::cout << sol.myAtoi("42") << std::endl; // 42 std::cout << sol.myAtoi(" -042") << std::endl; // -42 std::cout << sol.myAtoi("1337c0d3") << std::endl; // 1337 std::cout << sol.myAtoi("-91283472332") << std::endl; // -2147483648 return 0;}Time & Space Complexity
- Time complexity:
O(N)— Single linear pass over characters in string. - Space complexity:
O(1)
Why Brute Force Doesn't Scale:
Single linear pass with proactive threshold checking eliminates 64-bit casting.
Zero memory allocations; runs strictly in registers.