[LeetCode By Go 66]202. Happy Number

题目

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
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/25fe0bf4776a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞