Title: Happiness number


Write an algorithm to determine if a number is a "happiness number." A "happy number" is defined as replacing a positive integer each time with the sum of the squares of the numbers in each of its positions, and then repeating the process until the number becomes 1, possibly indefinitely. If you can change it to 1, then that number is happiness.Copy the code

Example:


Input: 19 Output: true Description: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1Copy the code

Think about:


A map is used to store the sum of squares calculated each time. Any repetition indicates that the number is looped. Break returns false. The sum of the squares of the bits is not repeated until the result is 1 and the loop ends and returns true.Copy the code

Implementation:


class Solution {
    public boolean isHappy(int n) {
        Map<Integer, Integer> map = new HashMap<>();
        boolean flag = true;
        while (n != 1) {
            int temp = n;
            n = 0;
            while (temp > 0) {
                n += Math.pow(temp % 10, 2);
                temp /= 10;
            }
            if (map.get(n) == null) {
                map.put(n, n);
            } else {
                flag = false;
                break;
            }
        }
        return flag;
    }
}Copy the code