Smartest way to judge a loop


  • 1
    H
        class Solution {
    public:
        bool isHappy(int n){
        	int low=n,fast=n;
        	while(1)
        	{
        		int temp=0;
        		while(low)
        		{
        			int l=low%10;
        			temp+=l*l;
        			low/=10;
        		}
        		low=temp;
        		temp=0;
        		while(fast)
        		{
        			int f=fast%10;
        			temp+=f*f;
        			fast/=10;
        		}
        		fast=temp;
        		temp=0;
        		while(fast)
        		{
        			int f=fast%10;
        			temp+=f*f;
        			fast/=10;
        		}
        		fast=temp;
        		if(low==1 || fast==1) return true;
        		if(fast==low) return false;
        	}
        }
    };
    

    I used to miss the questions about how to judge a loop in Leetcode.I admit that I could not figure out the questions forever if i didn't search the answer.
    But fortunately,i understand it and absorb it and i use it frequently.
    How smart the man is who come out the idea of low and fast pointer.


  • 0
    H

    this is very fast!!!!


  • 0

    I think you're the one who came up with low and fast. Everyone else uses slow and fast.

    Also, not sure what you mean with "smartest", but checking low==1 || fast==1 is not smart :-P


  • 0
    H

    lol~~ forgive for my poor english,I just feel so pleased for solving the problem.But why would you say that 'low==1 || fast==1' is a stubied way?


  • 0

    The low==1 part is pointless. If low is 1, then fast is also 1. So just checking fast==1 is better.


  • 0
    H

    thanks for your advice!


  • 0
    R
    This post is deleted!

  • 0
    R

    I'm sorry, but I want to upvote this post.
    Sorry again.


  • 0
    H

    i'm sorry to you ! shabi naocan


  • 0
    R

    cao ni ma. gun ni ma bi


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.