• 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.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/happy-number
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这道题的难点我觉得就是,当各个数字的平方和sum不等于1时,不能直接退出。但是继续循环下去的时候又容易进入了一个死循环,因此,我们可以设置一个set来存储出现过的平方和,当新算出来的平方和已经存在于此集合时,证明即将进入死循环,所以可以返回false,如果此平方和未曾出现过时,继续判断,同时把此数添加至set里面,并且把n更新为sum.

    代码如下:

    class Solution {
        public boolean isHappy(int n) {
            Set<Integer> temp = new HashSet<>();
            while(true)
            {
                int sum = 0;
                while(n != 0)
                {
                   int m = n % 10;
                    sum += m * m;
                    n /= 10;
                }
                if(sum == 1)
                {
                    return true;
                }
                else if(temp.contains(sum))
                {
                    return false;
                }
                else
                {
                    temp.add(sum);
                    n= sum;
                }
            }
        }
    }
  • 相关阅读:
    第13次作业--邮箱的正则表达式
    第11次作业--字符串处理
    第10次作业
    找回感觉的 练习
    《java技术》第十次作业
    《java》技术 第九次作业
    《java技术》第八次作业
    《java技术》第七次作业
    java实验六作业
    第五次实验作业
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/11853951.html
Copyright © 2020-2023  润新知