Leetcode Happy Number

來源:互聯網
上載者:User

標籤:

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
解題思路:

這道題定義了一種快樂數,就是說對於某一個正整數,如果對其各個位上的數字分別平方,然後再加起來得到一個新的數字,再進行同樣的操作,如果最終結果變成了1,則說明是快樂數,如果一直迴圈但不是1的話,就不是快樂數,那麼現在任意給我們一個正整數,讓我們判斷這個數是不是快樂數,題目中給的例子19是快樂數,那麼我們來看一個不是快樂數的情況,比如數字11有如下的計算過程:

1^2 + 1^2 = 2
2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^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又出現了,那麼之後的數字又都會重複之前的順序,這個迴圈中不包含1,那麼數字11不是一個快樂數,發現了規律後就要考慮怎麼用代碼來實現,我們可以用雜湊表來記錄所有出現過的數字,然後每出現一個新數字,在雜湊表中尋找看是否存在,若不存在則加入表中,若存在則跳出迴圈,並且判斷此數是否為1,若為1返回true,不為1返回false。

 Java code:

第一種:

public boolean isHappy(int n) {        // the key to solve this problem is to determine where to stop loop        if(n<=0) { return false; }        if(n == 1){ return true; }                HashSet<Integer> result = new HashSet<Integer>();        //n > 1        while(n!=1) {            result.add(n);            int sum = 0;            while(n>0) {                sum += (n%10) * (n%10);                n = n/10;            }            if(sum == 1) {                return true;             }            if(result.contains(sum)) {                break;            }            n = sum;        }        return false;    }

第二種:(參考他人的,更為簡潔明了)

 public boolean isHappy(int n) {        HashSet<Integer> happy = new HashSet<Integer>();        int sum = 0;        while(!happy.contains(n)){            sum =0;            happy.add(n);            int tmp = 0;            while(n > 0){                tmp = n % 10;                n = n / 10;                sum += tmp*tmp;            }            if(sum == 1){                return true;            }             n = sum;        }        return false;    }

Reference:

1. http://www.cnblogs.com/grandyang/p/4447233.html

2. https://sisijava.wordpress.com/2015/05/26/leetcode-happy-number/

 

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.