Same solution but in Swift, RunTime Error.


  • 0

    I checked over and over again, just the same solution with others in the Discuss board. Anyone know why I can't pass the test?

    func combinationSum4(nums: [Int], _ target: Int) -> Int {
        let nums = nums.sort()
        var res = Array(count: target + 1, repeatedValue: 0)
        res[0] = 1
        for i in 1...target {
            for n in nums {
                if n <= i {
                    res[i] += res[i - n]
                }else {
                    break
                }
            }
        }
        return res[target]
    }
    

  • 0
    F

    Because in Java, int type is 32-bit while in Swift, it's either 32-bit or 64-bit. On most iOS devices, it's 64-bit. Thus, we need to check for overflow/underflow cases based on 32-bit int manually.

    Below is the function I added to check for those edge cases.

    func handleException(_ val: Int) -> Int {
    let min = -1 * Int(pow(Double(2),Double(31)))
    let max = Int(pow(Double(2),Double(31))) - 1
    if val > max {
    return Int(Int32(bitPattern: UInt32(val)))
    } else if val < min {
    return val - min + max + 1
    } else {
    return val

        }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.