算法探索_快乐数

问题描述:

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

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

如果 n 是快乐数就返回 True ;不是,则返回 False 。

示例:

输入:19
输出:true
解释:
1^{2}+ 9^{2} = 82
8^{2} + 2^{2} = 68
6^{2} + 6^{2} = 100
1^{2}+ 0^{2} + 0^{2} = 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/happy-number

解决思路:

1.int转String  然后反转依次累加

2.递归循环执行

3.总结规律为,递归10次以上的为非快乐数

注意:

因为是递归实现,所以isOk 全局变量不可以省略

假如不声明isOk变量,直接在方法最后写 return false;

会使递归到最后内循环返回了true,却因为外层的return false而最终返回false。

    /*
     *作者:赵星海
     *时间:2020/8/19 16:01
     *用途:快乐数
     */
    int count = 10;
    boolean isOk = false;
    public boolean isHappy(int n) {
        System.out.println(count + "-----");
        if (count == 0) return isOk;
        count--;
        String thisStr = String.valueOf(n);
        int thisInt = 0;
        for (int i = 0; i < thisStr.length(); i++) {
            thisInt += (Integer.parseInt(thisStr.substring(i, i + 1))) * (Integer.parseInt(thisStr.substring(i, i + 1)));
            System.out.println(thisStr + "第" + i + "次 结果:" + thisInt);
            if (i == thisStr.length() - 1) {
                if (thisInt == 1) {
                    isOk = true;
                    return isOk;
                }
                isHappy(thisInt);
            }
        }
        return isOk;
    }

猜你喜欢

转载自blog.csdn.net/qq_39731011/article/details/108103095
今日推荐