Likou 202. Happy Number

Title description

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

"Happy number" is defined as: For a positive integer, every time the number is replaced with 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 never changes. To 1. If it can be changed to 1, then this number is a happy number.

If n is a happy number, return True; if not, return False.

Example

示例:

输入:19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Problem solving ideas

This question uses the fast and slow pointer method: the slow pointer performs one happy number conversion once, and the fast pointer performs two happy number conversions at a time.
If the fast pointer is equal to the slow pointer, either it is a loop or both are 1 (the slow pointer catches up with the fast pointer), return Just judge.

Code

int create(int n){
    
    
    int ret=0;
    while(n){
    
    
        int temp=0;
        temp=n%10;
        ret+=temp*temp;
        n/=10;
    }return ret;
}


bool isHappy(int n){
    
    
    int slow=create(n);
    int fast=create(create(n));
    while(slow!=fast){
    
    
        slow=create(slow);
        fast=create(create(fast));
    }
    return  slow==1;
   
}

link

Guess you like

Origin blog.csdn.net/qq_44722674/article/details/112389744