Swift solution


  • 0
    M

    class HappyNumber {
    func isHappy(_ n: Int) -> Bool {
    if n < 0 { return false }
    var intArray = String(n).flatMap{Int(String($0))}
    var result = 0
    var repeatedArray = Int
    while intArray.count > 0 {
    intArray.forEach{ result += $0 * $0 }
    if !repeatedArray.contains(result) {
    repeatedArray.append(result)
    if result == 1 {
    return true
    }else {
    //if count > result { return false }
    intArray = String(result).flatMap{Int(String($0))}
    result = 0
    }
    }else { return false }
    }
    return false
    }
    }


Log in to reply
 

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