48ms Simple Swift solution


  • 0
    func countBits(num: Int) -> [Int] {
    if num == 0 {
        return [0]
    }
    var count = [0,1]
    var i = 2
    while i <= num {
        let n1 = i >> 1
        let n2 = i % 2
        count.append(count[n1] + count[n2])
        i += 1
    }
    return count
    }

  • 0
    T

    You solution can reach to 44ms, just add something.
    like:

    func countBits(num: Int) -> [Int] {
        if num == 0 {
            return [0]
        }
        var **result:[Int]** = [0,1]
        var i = 2
        while i <= num {
            let quotient = i >> 1
            let remainder = i % 2
            result.append(result[quotient] + result[remainder])
            i++
        }
        return result
    }

  • 0

    @Tong_hdj Do you mean add the type of the variable, result: [Int]? But Stanford professor Paul Hegarty said, if a variable's type can be inferred from the value, it's better not to write the type explicitly.

    And btw, i++ is deprecated, it will be i += 1 in Swift 3.


Log in to reply
 

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