Happy Number
- leetcode: Happy Number
Write an algorithm to determine if a number is “happy”.
Example: 19 is a happy number
- $$1^2 + 9^2 = 82$$
- $$8^2 + 2^2 = 68$$
- $$6^2 + 8^2 = 100$$
题解
根据指定运算规则判断输入整数是否为『happy number』,容易推断得知最终要么能求得1,要么为环形队列不断循环。
第一种情况容易判断,第二种情况即判断得到的数是否为环形队列,也就是说是否重复出现,这种场景使用哈希表轻易解决。
有限迭代次数一定终止,时间和空间复杂度均为 O(1).