lintcode:快乐数

快乐数

写一个算法来判断一个数是不是"快乐数"。

一个数是不是快乐是这么定义的:对于一个正整数,每一次将该数替换为他每个位置上的数字的平方和,然后重复这个过程直到这个数变为1,或是无限循环但始终变不到1。如果可以变为1,那么这个数就是快乐数。

样例

19 就是一个快乐数。

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

解题

定义最大循环次数方法
public class Solution {
    /**
     * @param n an integer
     * @return true if this is a happy number or false
     */
    public boolean isHappy(int n) {
        // Write your code here
        if(n<=0)
            return false;
        if(n==1)
            return true;
        ArrayList<Integer> list = new ArrayList<Integer>();
        int nextNum = n;
        int limit = 100;
        while(limit>0){
            nextNum = nextNum(nextNum);
            if(nextNum == 1)
                return true;
            limit--;
        }
        return false;
    }
    public int nextNum(int n){
        int nextNum = 0;
        while(n!=0){
            nextNum +=(n%10)*(n%10);
            n/=10;
        }
        return nextNum;
    }
}

用TreeSet保存链表上的数,当出现循环而不到1 一定不是快乐数

public class Solution {
    /**
     * @param n an integer
     * @return true if this is a happy number or false
     */
    public boolean isHappy(int n) {
        // Write your code here
        if(n<=0)
            return false;
        if(n==1)
            return true;
        TreeSet<Integer> set = new TreeSet<Integer>();
        int nextNum = n;
        while(set.add(nextNum)){
            nextNum = nextNum(nextNum);
            if(nextNum == 1)
                return true;
        }
        set.clear();
        return false;
    }
    public int nextNum(int n){
        int nextNum = 0;
        while(n!=0){
            nextNum +=(n%10)*(n%10);
            n/=10;
        }
        return nextNum;
    }
}

这样增加了空间复杂度

Project Euler 92:Square digit chains  

有这样的一句话:任何一个到达1或89的数字链都会陷入无尽的循环。更令人惊奇的是,从任意数开始,最终都会到达1或89。

所以直接判断是否能够到达1 还是89,到达1就是快乐数,达到89就不是的了

public class Solution {
    /**
     * @param n an integer
     * @return true if this is a happy number or false
     */
    public boolean isHappy(int n) {
        // Write your code here
        if(n<=0)
            return false;
        if(n==1)
            return true;
        int nextNum = n;
        while(true){
            nextNum = nextNum(nextNum);
            if(nextNum == 1)
                return true;
            if(nextNum == 89)
                return false;
        }

    }
    public int nextNum(int n){
        int nextNum = 0;
        while(n!=0){
            nextNum +=(n%10)*(n%10);
            n/=10;
        }
        return nextNum;
    }
}

 

 
原文地址:https://www.cnblogs.com/bbbblog/p/5349932.html