(LeetCode) 66. Plus One

Plus One

  • Explore : Interview > Top Interveiw Questions > Easy Collection
  • 분류 : Array
  • 난이도 : Easy

Problem

Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1

1
2
3
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2

1
2
3
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Example 3

1
2
Input: digits = [0]
Output: [1]

Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9

Solution

Exapnder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
fun plusOne(digits: IntArray): IntArray {
digits.reverse()
var list = digits.toMutableList()
list[0] += 1

for (i in 0 until list.size) {
if (list[i] == 10) {
list[i] = 0
if (i + 1 == list.size) {
list.add(1)
} else {
list[i + 1] += 1
}
}
}
val result = list.toIntArray()

result.reverse()
return result
}
}

Point of Thinking

  • element가 9인 경우 자릿수를 올려줘야한다.
  • Array로 작업할 경우 사이즈를 늘려주어야 하는 케이스가 있으므로 List로 전환하면 작업이 편하다.
  • 최악의 input data는 9, 9, …, 9이다.