標籤:happynum leetcode square sum
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.
Example: 19 is a happy number
12+92=82
82+22=68
62+82=100
12+02+02=1
意思:判斷一個整數的所有數字平方和Sum是否為1,如果不是迴圈計算Sum的所有數位平方和,要麼最終得到1、要麼無限迴圈。如果是1就是happyNum。
演算法思想
計算過程中用hashtable儲存不是happyNumber的數字,每次計算之前查表判斷是否為happyNum。如果不是happyNum就迴圈計算,如果是則停止。
演算法實現
import java.util.Hashtable;public class Solution { public boolean isHappy(int n) { boolean happyNum = false; Hashtable<Integer, Boolean> badNumDic = new Hashtable<Integer, Boolean>(); int sum = 0; while (!happyNum) { sum = 0; while (n > 0) { sum += (n % 10) * (n % 10); n = n / 10; } System.out.println(sum); if (sum != 1) { if (badNumDic.containsKey(sum)) break; badNumDic.put(sum, false); } else { happyNum = true; } n = sum; } return happyNum; }}
演算法時間
這裡表面看上去時間複雜度為兩層迴圈,實際上:
- 外層迴圈的計算是一個有限常量
例如隨便給一個數25,他的計算過程如下:
1^2+9^2 = 29
2^2+9^2 = 85
8^2 + 5^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89(和第三步相同,如此反覆,而在程式中由於我們儲存在hashtable中,所以至此結束)
- 內層迴圈至多為最大整數2147483647的位元10,同樣為常量
已耗用時間為T(n) = O(1)
示範結果
public static void main(String[] args) { Solution hn = new Solution(); System.out.println(hn.isHappy(11111)); }
5
25
29
85
89
145
42
20
4
16
37
58
89
false
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【LeetCode】Happy Number