題目
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
}
}
}