LeetCode algorithm_C++——Happy Number

Write an algorithm to determine whether a number n is a happy number.

"Happy number" is defined as:
For a positive integer, each time the number is replaced by the sum of the squares of the numbers in each position.
Then repeat this process until the number becomes 1, or it may be an infinite loop but it never becomes less than 1.
If the result of this process is 1, then the number is a happy number.

Returns true if n is a happy number; otherwise, returns false.

Example 1:
Input: n=19
Output: true
Explanation:
12+92=82
82+22=68
62+82=100
12+02+02=1

Example 2:
Input: n = 2
Output: false

    int sum = 0;
    while (n > 0)
    {
    
    
        int bit = n % 10;
        sum += bit * bit;
        n = n / 10;
    }
    return sum;
}

bool isHappy(int n) {
    
    
    int slow = n, fast = n;
    do {
    
    
        slow = bitSquareSum(slow);
        fast = bitSquareSum(fast);
        fast = bitSquareSum(fast);
    } while (slow != fast);

    return slow == 1;
}

Guess you like

Origin blog.csdn.net/weixin_43945471/article/details/132723108