快乐数

来源:互联网 发布:js 返回首页清除历史 编辑:程序博客网 时间:2024/05/29 18:00

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

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

19 就是一个快乐数。

1^2 + 9^2 = 828^2 + 2^2 = 686^2 + 8^2 = 1001^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
        //在计算过程中 在算出1之前如果得到的结构已经在之前的记录中出现过
        //则一定不是快乐数
        //用链表保存已经出现过的数字
        int temp = n;
        LinkedList<Integer> linkedList = new LinkedList<Integer>(); 
        linkedList.add(temp);
        while (true) {
            temp = getNext(temp);
            if (temp == 1) {
                return true;
            } else if (linkedList.contains(temp)) {
                return false;
            }
            linkedList.add(temp);
        }
    }
    //获取计算后的下一个数
    public int getNext(int n){
        int result = 0;
        while(n>0){
            result += (n % 10)*(n % 10);
            n = n / 10;
        }
        return result;
    }
}
/*
1、如果一个数“不快乐”,则它计算到后面必然陷入到这个循环里:4, 16, 37, 58, 89, 145, 42, 20, 4, ...
2、对于一个大于243的数字来说,它的下一个数字一定比它小。这是因为一个大于1000的数字,它的下一个数字一定比它小,而对于1000以下最大的数字999,它的下一个数字是243,所以1000以下数字的下一个数字也只可能小于或等于243
while (true) {
            temp = getNext(temp);
            if (temp > 243) {
                continue;
            } else if (temp == 4 || temp == 16 || temp == 37 || temp == 58 ||
                temp == 89 || temp == 145 || temp == 42 || temp == 20) {
                return false;
            } else if (temp == 1) {
                return true;
            }
        }
        */
0 0
原创粉丝点击