Skip to content

Commit 15f8100

Browse files
anonimakignacio-chiazzo
authored andcommitted
Added Happy Number
1 parent b15c30c commit 15f8100

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
Happy Number
3+
https://leetcode.com/problems/happy-number/
4+
5+
Write an algorithm to determine if a number n is happy.
6+
7+
A happy number is a number defined by the following process:
8+
9+
Starting with any positive integer, replace the number by the sum of the squares of its digits.
10+
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
11+
Those numbers for which this process ends in 1 are happy.
12+
13+
Return true if n is a happy number, and false if not.
14+
15+
Example 1:
16+
Input: n = 19
17+
Output: true
18+
Explanation:
19+
12 + 92 = 82
20+
82 + 22 = 68
21+
62 + 82 = 100
22+
12 + 02 + 02 = 1
23+
24+
Example 2:
25+
Input: n = 2
26+
Output: false
27+
28+
29+
*/
30+
31+
/**
32+
* @param {number} n
33+
* @return {boolean}
34+
*/
35+
var isHappy = function(n) {
36+
return checkHappyNumber(n);
37+
};
38+
39+
function checkHappyNumber(n){
40+
strNumber = n.toString();
41+
splitNumber = strNumber.split("");
42+
if(splitNumber.length <= 1){
43+
return (n <= 1)? true:false;
44+
}
45+
const digit = splitNumber.reduce((a,b)=> parseInt(a) + Math.pow(parseInt(b),2),0);
46+
return checkHappyNumber(digit)
47+
}
48+
49+
module.exports.isHappy = isHappy;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const assert = require('assert');
2+
const isHappy = require('../../LeetcodeProblems/Algorithms/Happy_Number').isHappy;
3+
4+
var test = function () {
5+
assert.equal(isHappy(19),true);
6+
assert.equal(isHappy(2),false);
7+
}
8+
9+
module.exports.test = test;

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ To run a specific problem in your console run `node <problem_file_path>` (e.g.
8686
| [Permutations With Duplicates ](/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js) | | |
8787
| [Deletion Distance](/LeetcodeProblems/Algorithms/Deletion_Distance.js) | | |
8888
| [Award Budget Cuts](/LeetcodeProblems/Algorithms/Award_Budget_Cuts.js) | | |
89+
| [Happy Number](https://leetcode.com/problems/happy-number/) | Easy | https://leetcode.com/problems/happy-number/ |
8990

9091
### Sorting Algorithms
9192
| Algoritmhs |

0 commit comments

Comments
 (0)