Happy Number

描述

Write a function to determine if a number is "happy number".

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=821^2 + 9^2 = 82

82+22=688^2 + 2^2 = 68

62+82=1006^2 + 8^2 = 100

12+02+02=11^2 + 0^2 + 0^2 = 1

分析

这题找到规律后就简单了。如果右边的出现了某个重复的数,但不是1,说明会无限循环下去,这个数就不是快乐数,如果是1,则是快乐数。

代码

  1. // Happy Number
  2. // Time complexity: ?, Space complexity: ?
  3. public class Solution {
  4. public boolean isHappy(int n) {
  5. final Set<Integer> existed = new HashSet<>();
  6. while (true) {
  7. int sum = 0;
  8. while (n > 0) {
  9. int digit = n % 10;
  10. sum += digit * digit;
  11. n /= 10;
  12. }
  13. if (existed.contains(sum)) {
  14. return sum == 1;
  15. } else {
  16. existed.add(sum);
  17. n = sum;
  18. }
  19. }
  20. }
  21. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/number-theory/happy-number.html