HàPhan 河

Day 2 of 30 days Leetcode challenge

Happy Number

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.


Solution:

There's a endless loop means the result already appeared once. So just keep track all results.

class Solution {
    func isHappy(_ n: Int) -> Bool {
        var seen = Set<Int>()
        var val = n
        
        while !seen.contains(val) {
            seen.insert(val)
            val = val.modified()
            
            if val == 1 {
                return true
            }
        }
        
        return false
    }
}

extension Int {
    func modified() -> Int {
        var number = self
        var result: Int = 0
        while number > 0 {
            result += (Int(pow(Double(number % 10), 2)))
            number = number / 10
        }
        return result
    }
}

Comments