天天看點

LeetCode程式設計練習 - 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

       定義一種快樂數,就是說對于某一個正整數,如果對其各個位上的數字分别平方,然後再加起來得到一個新的數字,再進行同樣的操作,如果最終結果變成了1,則說明是快樂數,如果一直循環但不是1的話,就不是快樂數。數字19就是一個快樂數。

思路:     解決方案中用到了哈希集HastSet<T>,HastSet<T>相似與List<T>,不過哈希集無排序的功能,是以數學Set集合為基礎,可提高集合的運算,無法向裡面添加重複的資料。 Contains用來判斷元素是否存在。在使用的時候要注意HashSet是有緩存的,第一次執行完後會緩存所有的HashSet,以後再調用Contains比較的時候使用緩存的Hashset,是以HashSet最好隻用來存儲不可變對象,否則Contains方法的傳回值是不準确的。最後的傳回值恒等于1,是為了将bool值轉換為int型,對于不可變類要盡量滿足1,避免Set比較時出現問題。     為確定嚴謹性,先判斷數值是否是一個正數,然後再執行下一步,定義一個HastSet<int>哈希集用來儲存中間出現的結果。判斷數值不為1并且不能重複出現,若數值是大于0的數,便對數值的各個位平方相加。在對于對數值的運算這方面我的想法與解決方案不同,但是我的想法顯然是錯誤的,輸出結果不符。

LeetCode程式設計練習 - Happy Number學習心得

     解決方案:

LeetCode程式設計練習 - Happy Number學習心得
LeetCode程式設計練習 - Happy Number學習心得