码迷,mamicode.com
首页 > 移动开发 > 详细

happy number

时间:2019-11-13 23:56:47      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:happy   联系   which   this   equals   for   color   with   follow   

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;
            }
        }
    }
}

 

happy number

标签:happy   联系   which   this   equals   for   color   with   follow   

原文地址:https://www.cnblogs.com/WakingShaw/p/11853951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!