π‘ LeetCode 66 - Plus One
π‘ LeetCode 66 - Plus One
λ¬Έμ
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.
μ μΆλ ₯ μμ
β μμ 1
1
2
3
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].
β μμ 2
1
2
3
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].
β μμ 3
1
2
3
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].
μ μ½μ‘°κ±΄
1 <= digits.length <= 100
0 <= digits[i] <= 9
- digits does not contain any leading 0βs.
μμ± μ½λ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int[] plusOne(int[] digits) {
// 1. λ³μ μ μΈ λ° μ΄κΈ°ν
int num = 0;
int idx = 0;
int[] result = new int[length];
// 2. νλΌλ―Έν° λ°°μ΄ intν λ³μλ‘ μ ν
for (int digit : digits) num = num * 10 + digit;
num += 1;
// 3. κ° μλ¦Ώμ ꡬν΄μ λ°°μ΄μ μ μ¬
int length = (int) Math.log10(num) + 1;
while (num > 0) {
result[idx++] = num / (int) Math.pow(10, --length);
num %= Math.pow(10, length);
}
// 4. λ°ν
return result;
}
}
- μνμ μ΄μ©ν΄μ νμ΄λ³΄κ³ μΆμλλ°, μμ λ°λ‘κ° μμλ€.
9_876_543_210
μint
νμ λ²μλ₯Ό λ²μ΄λμOverflow
κ° λ°μνλ€.long
μΌλ‘ ν λ³νν΄μ ν μλ μκ² μ§λ§, λ€λ₯Έ λ°©μμΌλ‘ μ κ·Όνλ€.
κ°μ μ½λ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public int[] plusOne(int[] digits) {
// 1. λ³μ μ μΈ λ° μ΄κΈ°ν
int length = digits.length;
// 2. λ°°μ΄ κ±°κΎΈλ‘ μννλ©° μ¬λ¦Ό λ°μνλ μ§ νμΈ λ° μ²λ¦¬
for (int i=length - 1; i>=0; i--) {
if (digits[i] + 1 >= 10) {
// 1μ λνμ λ 10 μ΄μμ΄λΌλ©΄ 0 λμ
digits[i] = 0;
if (i == 0) {
// μ΅κ³ μλ¦ΏμλΌλ©΄ λ°°μ΄ ν¬κΈ° λλ¦¬κ³ 1 λμ
digits = Arrays.copyOf(digits, length + 1);
digits[0] += 1;
break;
}
} else {
// 1μ λνμ λ 10 λ―Έλ§μ΄λΌλ©΄ 1 λ§μ
digits[i] += 1;
break;
}
}
// 3. λ°ν
return digits;
}
}
- λ°°μ΄μ μ¬μ΄μ¦λ₯Ό λλ €κ°λ©° ν΄κ²°νμλ€.
This post is licensed under CC BY 4.0 by the author.