[LeetCode]202. Happy Number

來源:互聯網
上載者:User

標籤:write   ops   尋找   contains   stay   儲存   表示   where   否則   

題目描述:

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

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

思路:

思路:一個快樂數指的是各位元字的平方的和加起來,不斷計算,最終收斂為1。對於某一個正整數,如果對其各個位上的數字分別平方,
然後再加起來得到一個新的數字,再進行同樣的操作,如果最終結果變成了1,則說明是快樂數,如果一直迴圈但不是1的話,就不是快樂數,否則會陷入死迴圈。
給出一個整數,判斷是否為快樂數。
如果不是快樂數。如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的死迴圈
可以用set來記錄所有出現過的數字,然後每出現一個新數字,在set中尋找看是否存在,若不存在則加入表中,
若存在則跳出迴圈,並且判斷此數是否為1,若為1返回true,不為1返回false
set中不存在重複的對象
首先判斷是否小於0.小於0則返回false
當n不等於1時,將n儲存到set內,對n計算各位元字的平方和,記為新的n。判斷n是否在set中出現過,如果出現過則表示陷入迴圈了。返回false
否則將n存入set中去,繼續判斷新的n

第二種方法是:
非快樂數必然在迴圈中出現4,只需判斷是否在迴圈中n出現過4,出現則false

 1 public class Solution202 { 2     public boolean isHappy(int n) { 3         HashSet<Integer> set  = new HashSet<>(32); 4         if(n <= 0) return false; 5         while(n!=1){ 6             int tmp = 0; 7             set.add(n); 8             while(n>0){ 9                 tmp+=(n%10)*(n%10);10                 n/=10;11             }12             n = tmp;13             if(set.contains(n)) break;14             else {15                 set.add(n);16             }17         }18         return n == 1;19         /*第二種方法:判斷迴圈中是否出現4即可20           while (n != 1 && n != 4) {21             int t = 0;22             while (n>0) {23                 t += (n % 10) * (n % 10);24                 n /= 10;25             }26             n = t;27         }28         return n == 1;29         */30     }31     public static void main(String[] args) {32         // TODO Auto-generated method stub33         Solution202 solution202 = new Solution202();34         int n = 19;35         System.out.println(solution202.isHappy(n));36     }37 38 }

 

[LeetCode]202. 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.