תיאור השאלה
You are given a large integer represented as an array digits, where each element is one digit, ordered from most significant to least significant, with no leading zeros. Increment the integer by one and return the resulting array of digits.
איך פותרים?
עוברים מהספרה האחרונה אחורה. ספרה קטנה מ־9 פשוט מגדילים ומחזירים. ספרה 9 הופכת ל־0 והנשא ממשיך שמאלה. אם כל הספרות היו 9, מוסיפים 1 בהתחלה. סיבוכיות: O(n).
פתרון קוד
JavaScript
Python
function plusOne(digits) {
for (let i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
return [1, ...digits];
}
לעבור את ראיון העבודה הבא שלך בהצלחה
קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.