[LeetCode] 202. Happy Number

Write an algorithm to determine if a number n 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.

Return True if n is a happy number, and False if not.

寻找快乐数字。快乐数字的定义是如果每一位上的数字的平方相加最后能成为1,那么这个数字就是快乐数字。

思路就是按照其规则做运算,如果最后是false,中间一定是有死循环,此处可以用hashset记录出现过的和。如果最后能算成1,就是true。

时间O(1) - 因为稍微算几次就会出来,不会因着input变大而变大

空间O(n) - 用了一个hashmap

Java实现

 1 class Solution {
 2     public boolean isHappy(int n) {
 3         HashSet<Integer> set = new HashSet<>();
 4         while (n != 1) {
 5             int sum = 0;
 6             while (n > 0) {
 7                 sum += (n % 10) * (n % 10);
 8                 n /= 10;
 9             }
10             if (set.contains(sum)) {
11                 return false;
12             } else {
13                 set.add(sum);
14             }
15             n = sum;
16         }
17         return true;
18     }
19 }

JavaScript实现

 1 /**
 2  * @param {number} n
 3  * @return {boolean}
 4  */
 5 var isHappy = function (n) {
 6     let set = new Set();
 7     while (n !== 1) {
 8         let sum = 0;
 9         while (n > 0) {
10             sum += (n % 10) * (n % 10);
11             n = parseInt(n / 10);
12         }
13         if (set.has(sum)) {
14             return false;
15         } else {
16             set.add(sum);
17             n = sum;
18         }
19     }
20     return true;
21 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11670561.html