LeetCode程式設計練習
阿新 • • 發佈:2019-01-09
題目:
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集合為基礎,可提高集合的運算,無法向裡面新增重複的資料。