How to check if a number is a happy number in Swift

1 Answer

0 votes
import Foundation

// 8^2 + 2^2 = 68
// 6^2 + 8^2 = 100
// 1^2 + 0^2 + 0^2 = 1 = happy number

func sumOfSquares(_ n: Int) -> Int {
    return String(n)
        .compactMap { $0.wholeNumberValue }
        .map { $0 * $0 }
        .reduce(0, +)
}

func isHappy(_ n: Int) -> Bool {
    var seen = Set<Int>()
    var x = n

    while x != 1 && !seen.contains(x) {
        seen.insert(x)
        x = sumOfSquares(x)
    }

    return x == 1
}

let num = 82

if isHappy(num) {
    print("\(num) is a happy number")
} else {
    print("\(num) is NOT a happy number")
}



/*
run:

82 is a happy number

*/

 



answered Feb 24 by avibootz
edited Feb 24 by avibootz
...