Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

202. 快乐数 #79

Open
yankewei opened this issue Nov 27, 2020 · 1 comment
Open

202. 快乐数 #79

yankewei opened this issue Nov 27, 2020 · 1 comment
Labels
哈希表 题目包含哈希表解法 数学 题目类型为数学 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为  1,那么这个数就是快乐数。

如果 n 是快乐数就返回 True ;不是,则返回 False 。

示例:

输入:19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/happy-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 哈希表 题目包含哈希表解法 数学 题目类型为数学 简单 题目难度为简单 labels Nov 27, 2020
@yankewei
Copy link
Owner Author

func isHappy(n int) bool {
    m := make(map[int]bool)
    for {
	n = getNum(n)
	if n == 1 {
	    return true
	} else {
	    if m[n] {
		break
	    }
	    m[n] = true
	}
    }
    return false
}

func getNum(n int) int {
    var ret int

    for n > 9 {
	ret += (n % 10) * (n % 10)
	n = n / 10
    }
    ret += n * n
    return ret
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
哈希表 题目包含哈希表解法 数学 题目类型为数学 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant