【LeetCode】Happy Number

來源:互聯網
上載者:User

標籤: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;    }}
演算法時間

這裡表面看上去時間複雜度為兩層迴圈,實際上:

  1. 外層迴圈的計算是一個有限常量

例如隨便給一個數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中,所以至此結束)

  1. 內層迴圈至多為最大整數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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.