本文是在學習中的總結,歡迎轉載但請注明出處:http://blog.csdn.net/pistolove/article/details/45396585
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)題意為判斷給定的整數是不是為1個“快樂的數”,所謂快樂的數需要滿足1下幾個條件:將該整數的每一個位上的數字的平方相加得到1個新的整數,循環對新的整數進行上述操作,如果最后所得整數收斂于1,則這樣的數字為1個“快樂的數”。
(2)首先,判斷0肯定不是1個“快樂的數”;其次,對初始數字的每一個位上數的平方相加,循環進行前面的操作;需要注意的是,對可能會出現死循環的數字需要進行判斷,需要判斷循環的次數,這里通過測試得到循環次數為4,即如果4次循環進程中,每次所得數字中都不收斂于1,則判斷該數字不是1個“快樂的數”,否則,則是1個“快樂的數”;最后,對那些循環得到的結果為1的數字,直接返回true,即該數字是1個“快樂的數”。
(3)詳情見下方代碼。希望本文對你有所幫助。
算法代碼實現以下: