🐦🔥Beginner-Friendly Guide 'Plus One' – LeetCode 66 (C++ | Python | JavaScript)
Source: Dev.to
Problem Description
You are given an array digits that represents a non‑negative integer, where each element is a single digit and the most significant digit is at the beginning of the array.
The array has no leading zeros, except when the number itself is 0.
Your task is to add one to the integer and return the resulting array of digits.
Edge cases
- If a digit is less than
9, simply increment it and you’re done. - If a digit is
9, it becomes0and you carry1to the next digit on the left. - If all digits are
9(e.g.,[9,9,9]), the result should be a new array with a leading1followed by zeros (e.g.,[1,0,0,0]).
C++ Solution
class Solution {
public:
vector plusOne(vector& digits) {
for (int i = digits.size() - 1; i >= 0; --i) {
if (digits[i] List[int]:
for i in range(len(digits) - 1, -1, -1):
if digits[i] = 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
// All digits were 9
digits.unshift(1);
return digits;
};
Key Points
- Reverse Traversal: Start from the end of the array to handle carries correctly.
- Early Return: When a digit less than
9is found, increment it and return immediately—no further processing needed. - Array Manipulation: Inserting an element at the front (
insertin C++,unshiftin JavaScript, list concatenation in Python) is essential for the all‑9case.
This problem demonstrates how simple logic can manage “large integers” that would otherwise overflow standard integer types in many languages. It’s all about correctly handling the carry.