Golang Leetcode 202. Happy Number.go

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89012332

思路

可以证明的是,如果某一步的结果等于4,那么就会陷入无限循环
递归计算,判断最后结果就ok了

code

func isHappy(n int) bool {
	return isOne(n)
}
func getSum(n int) int {
	if n/10 == 0 {
		return n * n
	}
	return (n%10)*(n%10) + getSum(n/10)
}
func isOne(n int) bool {
	a := getSum(n)
	if a == 1 {
		return true
	} else if a == 4 {
		return false
	} else {
		return isOne(a)
	}
}

更多内容请移步我的repo: https://github.com/anakin/golang-leetcode

猜你喜欢

转载自blog.csdn.net/anakinsun/article/details/89012332
今日推荐