Programming/알고리즘 공부
[LeetCode] Plus One | 난이도: Easy
Cafe_Caramelo
2021. 9. 12. 21:14
반응형
문제
주어진 정수 배열 digits에 있는 값을 하나의 숫자로 보고 1을 더한 결과를 배열로 리턴한다.
배열에 담기는 숫자는 0부터 9까지이다.
만약 배열에 값 9만 담겨 있다고 가정해보자.( digits[9] ) 여기에 1을 더하면 10이 된다. 따라서 결과는 digits[1, 0]이 된다. 이렇게 자릿수가 바뀔 수 있다는 점에 유의해야 한다.
예시
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:
Input: digits = [0]
Output: [1]
Explanation: The array represents the integer 0.
Incrementing by one gives 0 + 1 = 1.
Thus, the result should be [1].
Example 4:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
답안
class Solution {
public int[] plusOne(int[] digits) {
int len = digits.length;
for(int i = len-1; i>=0; i--){
digits[i]++;
if(digits[i] <= 9){
return digits;
}else{
digits[i] = 0;
}
}
if(digits[0] == 0){
int[] res = new int[digits.length+1];
res[0] = 1;
return res;
}
return digits;
}
}
배열의 거꾸로 돌린다. 그 이유는 배열의 마지막 값에 1만 더하면 되기 때문이다.
만약 배열에 정수 9만 단독으로 있을 경우 자릿수 변화가 필요하다. 기존 배열보다 길이가 +1만큼 더 긴 새로운 배열을 선언하고 첫번째 인덱스에 1을 넣고 리턴한다.
반응형