Post

πŸ’‘ 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.