【題目描述】
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.
寫一個算法來判斷一個數(shù)是不是"快樂數(shù)"。
一個數(shù)是不是快樂是這么定義的:對于一個正整數(shù)典格,每一次將該數(shù)替換為他每個位置上的數(shù)字的平方和蜜另,然后重復(fù)這個過程直到這個數(shù)變?yōu)?,或是無限循環(huán)但始終變不到1。如果可以變?yōu)?褂删,那么這個數(shù)就是快樂數(shù)您宪。
【題目鏈接】
www.lintcode.com/en/problem/happy-number/
【題目解析】
判斷一個數(shù)字是否為Happy Number。這道題跟求無限循環(huán)小數(shù)很像芍躏,最好維護一個HashSet邪乍,假如遇見重復(fù),則返回false对竣。否則替換n為digits square root sum庇楞,當(dāng)n == 1時循環(huán)結(jié)束返回true。
【參考答案】