문제
Plus One - LeetCode
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.


- 정수의 각 자릿수를 나타내는 배열에서 그 정수에 1을 더한 값을 나타내는 배열 구하기
구현
- 맨 뒤에서부터 1을 더함
- 더했을 때 9가 넘으면 0을 주고 그 다음으로 넘어가서 반복 ( N )
- 반복이 끝난 후에도 더할 게 남아있으면 배열 맨 앞에 추가 ( N )
시간 복잡도
- O(N)
코드
func plusOne(digits []int) []int { carry := 1 for i:=len(digits)-1;i>=0;i-- { if digits[i] + carry > 9 { digits[i] = 0 } else { digits[i] = digits[i] + carry carry = 0 break } } if carry==1 { return append([]int{1},digits...) } return digits }
'알고리즘' 카테고리의 다른 글
[LeetCode] 409. Longest Palindrome (golang) (0) | 2021.06.12 |
---|---|
[LeetCode] 104. Maximum Depth of Binary Tree (golang) (0) | 2021.06.07 |
[LeetCode] 205. Isomorphic Strings (golang) (0) | 2021.06.02 |
[LeetCode] 572. Subtree of Another Tree (golang) (0) | 2021.06.01 |
[LeetCode] 455. Assign Cookies (golang) (0) | 2021.06.01 |
댓글