happy number

Write an algorithm to determine if a number is "happy".git

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
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。app

 

這道題的難點我以爲就是,當各個數字的平方和sum不等於1時,不能直接退出。可是繼續循環下去的時候又容易進入了一個死循環,所以,咱們能夠設置一個set來存儲出現過的平方和,當新算出來的平方和已經存在於此集合時,證實即將進入死循環,因此能夠返回false,若是此平方和不曾出現過期,繼續判斷,同時把此數添加至set裏面,而且把n更新爲sum.less

代碼以下:oop

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;
            }
        }
    }
}
相關文章
相關標籤/搜索