2024. 9. 20. 11:00ㆍ알고리즘/Leetcode
Solution
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Examples

Explanation
class Solution {
public int[] plusOne(int[] digits) {
int length = digits.length;
for(int i = length - 1; i >= 0; i--){
if(digits[i] < 9){
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] newArr = new int[length+1];
newArr[0] = 1;
return newArr;
}
}
In case the given array is [1, 2, 3]
If the digits[i] is less than 9, increment digits[i] and will directly return the array.
In case the given array is [2, 1, 9]
If the digits[i] is not less than 9, means that it only has to be 9 then digits is changed to zero. The for loop then iterates through the array and check for number whether it is less than 9 or not.
In case the given array is [9, 9, 9]
It will become [0, 0, 0] according to the above loop. To increment the array, make a new array with length + 1 and change the first value of array to 1 and return newArr, [1, 0, 0, 0].
'알고리즘 > Leetcode' 카테고리의 다른 글
| Two Sum (1) | 2024.09.24 |
|---|---|
| Move Zeroes (2) | 2024.09.23 |
| Intersection of Two Arrays II (1) | 2024.09.12 |
| Single Number (2) | 2024.09.05 |
| Rotate Array (3) | 2024.09.03 |