Quick and slow pointer usage exercise LeetCode: 202. Happy Tree

Method: Use the idea of ​​"fast and slow pointer" to find the cycle: "fast pointer" takes two steps at a time, and "slow pointer" takes one step at a time. When the two are equal, it is a cycle. At this point, judge whether it is a cycle caused by 1, if yes, it is a happy number, otherwise it is not a happy number.

 

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

A "happy number" is defined as: For a positive integer, every time the number is replaced by the sum of the squares of the numbers in each position, and then this process is repeated until the number becomes 1, or it may be an infinite loop but always changes Less than 1. If it can be changed to 1, then this number is a happy number.

Example: 

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

Participate the code

class Solution {
public:
    int bitSquareSum(int n) {
        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;
        while(slow != 1){
            slow = bitSquareSum(slow);
            fast = bitSquareSum(fast);
            fast = bitSquareSum(fast);
            if ( slow == fast) break;
        }
        return slow == 1;
    }
};

 

Guess you like

Origin blog.csdn.net/qq_40513792/article/details/104289048