1. 程式人生 > >LeetCode程式設計練習

LeetCode程式設計練習

題目:

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的數,便對數值的各個位平方相加。在對於對數值的運算這方面我的想法與解決方案不同,但是我的想法顯然是錯誤的,輸出結果不符。
     解決方案: