[LeetCode/66] Plus One - JAVA

이지환·2024년 4월 25일

알고리즘(leetcode)

목록 보기
2/2
post-thumbnail

📌 Problem

Algorithm Classification : Array
Difficulty Level : easy
Source : LeetCode - 66. Plus One

🦧 Problem Solving Approach

Add '1' to the last index of the array.

If the value at that index is 10, add '1' to the index one
position before it.

Repeat this process.
If the first index is '10', increase the size of the array.

💻 Code

class Solution {
    public int[] plusOne(int[] digits) {
        for(int i=0;i< digits.length;i++) {
            if(++digits[digits.length-i-1]!=10)
                return digits;
            digits[digits.length-i-1]=0;
        }
        digits = new int[digits.length+1];
        digits[0] = 1;
        return digits;
    }
}

🥇 Result

🎓 Conclusion

digits = new int[digits.length + 1];

I've recently discovered a method for expanding the size of an array by adding elements at the beginning, following the approach outlined earlier.

profile
takeitEasy

0개의 댓글