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 and replace the number by the Sum of the squares of its digits, and repeat the process until the number equals 1 (where it would stay), or it loops Endl essly in a cycle which does not include 1. Those numbers for which this process ends in 1 is happy numbers.
Example:19 is a happy number
- 1^2 + 9^2 = 82
- 8^2 + 2^2 = 68
- 6^2 + 8^2 = 100
- 1^2 + 0^2 + 0^2 = 1
https://leetcode.com/problems/happy-number/
The sum of squares of each digit, if equal to 1 is happy number, otherwise recursive return to find, encounter dead loop description is not. The general idea is to open a hash table, record the number of occurrences, and return False when a repetition is encountered. Using the code with a hash table, the single digit is used to make a list, and only 1 and 7 are happy number, others are not. So in order to get rid of the hash table, I directly write dead 1-9 results, because happy number of the operation of many intermediate results are single-digit, encountered single-digit can not be done.
1 /**2 * @param {number} n3 * @return {Boolean}4 */5 varIshappy =function(n) {6 if(n = = 1 | | n = = 7)return true;7 if(N < 10)return false;8n =n.tostring ();9 varNextnum = 0, TMP;Ten for(vari = 0; i < n.length; i++){ OneTMP =Math.floor (N[i]); ANextnum + = tmp *tmp; - } - returnIshappy (nextnum); the};
[Leetcode] [JavaScript] Happy number