LeetCode 202 Happy Number

题目:

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

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 

解法:

1. 利用set保存每次计算的结果,若出现1,则返回true,若出现已有元素,而没有出现1则说明会陷入循环,返回false

class Solution {
    public boolean isHappy(int n) {
        
        Set<Integer> set = new HashSet<>();
        int newn = 0;
        
        while(!set.contains(n))
        {
            set.add(n);
            newn = 0;
            while(n>0)
            {
                newn += (n%10)*(n%10);
                n /= 10;
            }
            if(newn==1) return true;
            
            n = newn;
        }
        
        return false;
        
    }
}
View Code

2. 参考了discussion的做法,经规律总结,当计算结果在10以内时,只有7和1才会是happy number

class Solution {
    public boolean isHappy(int n) {
        
        int newn = 0;
        
        while(n>9)
        {
            newn = 0;
            while(n>0)
            {
                newn += (n%10)*(n%10);
                n /= 10;
            }
            n = newn;
        }
        
        return n==7||n==1;
        
        
        
    }
}
View Code

3. 由于计算结果最终会形成一个循环,可以参照Floyd判圈算法的思想,设置一个slow一次计算一步,一个fast一次计算两步,则当走入循环,fast会在一圈以内追上slow,使得两者此时指向的结果相同

class Solution {
    public boolean isHappy(int n) {
        
        int slow = n;
        int fast = n;
        
        do{
            
            slow = helper(slow);
            fast = helper(helper(fast));
            
            if(slow==1||fast==1) return true;
            
        }while(slow!=fast);
        
        return false;
        
        
        
    }
    
    public int helper(int n)
    {
        int res = 0;
        while(n>0)
        {
            res += (n%10)*(n%10);
            n /= 10;
        }
        return res;
    }
}
View Code
原文地址:https://www.cnblogs.com/trymorel/p/12622790.html