Skip to content

Commit cdec2d4

Browse files
committed
feat: Add solution for happy number problem
1 parent 5661451 commit cdec2d4

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

easy/happy-number.test.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Problem: https://leetcode.com/problems/happy-number/
2+
// Doc: https://leetcode.com/problems/happy-number/solutions/5471203/determining-happy-numbers-efficiently/
3+
const isHappy = (n: number): boolean => {
4+
// I assume that we cannot use string conversion to make it challenging
5+
const visited: Record<number, boolean> = {};
6+
while (true) {
7+
if (n === 1) return true;
8+
if (n in visited) return false;
9+
visited[n] = true;
10+
11+
let sum = 0;
12+
let tmp = n;
13+
while (tmp > 0) {
14+
const remainder = tmp % 10;
15+
tmp = Math.floor(tmp / 10);
16+
sum += Math.pow(remainder, 2);
17+
}
18+
n = sum;
19+
}
20+
};
21+
22+
describe('Happy Number', () => {
23+
it('should return true if the number is happy', () => {
24+
expect(isHappy(19)).toBeTruthy();
25+
expect(isHappy(1)).toBeTruthy();
26+
expect(isHappy(7)).toBeTruthy();
27+
});
28+
29+
it('should return false if the number is not happy', () => {
30+
expect(isHappy(2)).toBeFalsy();
31+
expect(isHappy(3)).toBeFalsy();
32+
});
33+
});

0 commit comments

Comments
 (0)