Description
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.
Example: 19 is a happy number
image.png
Solution
很有意思的題啊,很糾結(jié)如何處理死循環(huán)翠订,經(jīng)點播發(fā)現(xiàn)可以使用一個HashSet做輔助瑰钮,存儲遇到過的數(shù)字扣囊。如果當(dāng)前數(shù)字已經(jīng)在HashSet中存在了昵慌,說明已經(jīng)陷入死循環(huán)棍苹,就可以返回false了兴垦;
class Solution {
public boolean isHappy(int n) {
if (n == 1) return true;
Set<Integer> inLoop = new HashSet<>(); // nums already met
while (inLoop.add(n)) { // if already in set, it returns false
n = sumOfSquares(n);
if (n == 1) return true;
}
return false;
}
public int sumOfSquares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
}