๋ฌธ์
Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
์ด์ ๋ ์ด๋ ๊ฒ Int Array ๋ String์ผ๋ก ์ฃผ๋ฉด์ ๋ง์ ์ ํ๋ผ๋ ๋ฌธ์ ๋ค์
๊ทธ๋ฅ Int ์๋ฃํ์ MAX ๊ฐ ๋ณด๋ค ๋ง์ ๊ฐ์ด ์ปค์ ธ์ ์ค๋ฒํ๋ก์ฐ ์ผ์ด๋๊ธฐ ๋๋ฌธ์ digit ๋ณ๋ก ์ฒ๋ฆฌํด์ผ ๋๋ ๋ฌธ์ ๋ก
๋ฐ๋ก ์๊ฐ์ด ๋ ๋ค.
carry ๋ณ์๋ฅผ ์ฌ์ฉํด ๋งจ์ฒ์ 1์ ๋ํ๊ณ carry ์ ๋ฌด์ ๋ฐ๋ผ ๊ฐ์ ๋ฐ๊ฟ์ค๋ค.
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
var arr = digits
var answer : [Int] = []
var carry = 0
for i in (0..<digits.count).reversed() {
var digit = arr[i] + carry
if i == digits.count - 1 { digit += 1 }
// print(digit, terminator: " " )
answer.append(digit%10)
carry = digit/10
}
if carry != 0 {
answer.append(carry)
}
return answer.reversed()
}
}
ํน์๋ ์ถ์ด Int ๋ก ๋ฐ๊พธ์ด +1 ๋ง ๋ํ ๋ค ๋ค์ Int array ๋ก ๋ง๋ค์ด ๋ฆฌํดํด ๋ณด์๋ค.
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
var number = digits.map{String($0)}.joined(separator: "")
var tmp = Int(number)! + 1
let answer = String(tmp).compactMap {$0.wholeNumberValue}
return answer
}
}
๋น์ทํ ๋ฐฉ์์ ๋ง์ ์ฝ๋์ด๋ค.
'Algorithm > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฏ Daily LeetCode Challenge Day_08 - 3Sum (0) | 2020.07.09 |
---|---|
๐ฏ Daily LeetCode Challenge Day_07 - Island Perimeter (0) | 2020.07.07 |
๐ฏ Daily LeetCode Challenge Day_05 - Hamming Distance (2) | 2020.07.06 |
๐ฏ Daily LeetCode Challenge Day_04 - Ugly Number II (0) | 2020.07.06 |
๐ฏ Daily LeetCode Challenge Day_03 - Prison Cells After N Days (0) | 2020.07.03 |
๋๊ธ