๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/LeetCode

๐Ÿ’ฏ Daily LeetCode Challenge Day_06 - Plus One

by HaningYa 2020. 7. 7.
728x90

 

Account Login - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


๋ฌธ์ œ

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
    }
}

 

์‘์•ˆ๋˜ ๋Œ์•„๊ฐ€ 

 

๋น„์Šทํ•œ ๋ฐฉ์‹์˜ ๋ง์…ˆ ์ฝ”๋“œ์ด๋‹ค.

 

Swift ๋ฐฐ์—ด ์ฒ˜๋ฆฌ

String ๊ณผ Int ๋ฅผ ๋„˜๋‚˜๋“œ๋Š” ๋ฐ์ดํ„ฐ ํƒ€์ž… ๋ณ€๊ฒฝ ๋ฐฐ์—ด ๋ฐ˜๋Œ€๋กœ ์ˆœํšŒ ๋ฐฐ์—ด์„ String์œผ๋กœ ๋ฆฌํ„ด ์ฝ”๋“œ import Foundation var arr1 : [Int] = [3,2,3,1,2,8,6,4,3,5,2,3,2,1] var arr2 : [Int] = [9,7,5,4,3,4,2,1,3,5,0,..

haningya.tistory.com

 

728x90

๋Œ“๊ธ€