题目
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
解题思路
建立一个map numMap,用于存放每次计算出的新值
每次计算一个新值后,判断该值是否为1,如果是1,则返回true
如果不是1,则判断该值在map中是否存在,如果存在,则返回false
否则将新值放入map中
代码
func getNewNum(num int) (newNum int) {
for ; num > 0 ; {
a := num % 10
num = num / 10
newNum += a * a
}
return newNum
}
func isHappy(n int) bool {
var numMap map[int]bool
numMap = make(map[int]bool)
var newNum int
newNum = n
for {
if 1 == newNum {
return true
}
newNum = getNewNum(newNum)
_, ok := numMap[newNum]
if ok {
return false
} else {
numMap[newNum] = true
}
}
}