String to Integer (atoi)
בינוני
שאלה מראיונות עבודה ממאגר שאלות של LeetCode שאלה מספר 8
Implement the `atoi` function, which converts a string to a 32-bit signed integer according to the following rules: - Discard leading whitespace. - Check for an optional sign (`+` or `-`). - Read in next digits until a non-digit character is encountered. - Clamp the integer to the range `[-2^31, 2^31 - 1]`.
פתרון קוד
JavaScript
Python
function myAtoi(s) {
const INT_MIN = -2147483648;
const INT_MAX = 2147483647;
let i = 0, n = s.length;
while (i < n && s[i] === ' ') i++;
let sign = 1;
if (i < n && (s[i] === '+' || s[i] === '-')) {
sign = s[i] === '-' ? -1 : 1;
i++;
}
let result = 0;
while (i < n && s[i] >= '0' && s[i] <= '9') {
const digit = s.charCodeAt(i) - 48;
result = result * 10 + digit;
const signed = sign * result;
if (signed > INT_MAX) return INT_MAX;
if (signed < INT_MIN) return INT_MIN;
i++;
}
return sign * result;
}הסבר וידאו כיצד לפתור את השאלה

לעבור את ראיון העבודה הבא שלך בהצלחה
קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.