Implement atoi: skip leading spaces, read an optional sign, then read digits until a non-digit. Clamp the result to the signed 32-bit range; return 0 if no digits were read.
Skip spaces, read a sign, then fold digits into the result. Before each multiply-by-10, check whether it would overflow and clamp right away.
1function myAtoi(s: string): number {2let i = 0, sign = 1, res = 0;3while (s[i] === " ") i++;4if (s[i] === "+" || s[i] === "-") sign = s[i++] === "-" ? -1 : 1;5while (i < s.length && s[i] >= "0" && s[i] <= "9") {6const d = +s[i++];7if (res > (2 ** 31 - 1 - d) / 10) return sign === 1 ? 2 ** 31 - 1 : -(2 ** 31);8res = res * 10 + d;9}10return sign * res || 0;11}
Skip a leading space.
Space: play/pause · ←/→: step