Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added two very basic TypeScript Algorithms #1314

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Binary Search/binary_search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const binarySearch = (
nums: number[],
s: number,
start: number = 0,
end: number = nums.length - 1,
): number => {
const mid = Math.floor((start + end) / 2);

if (nums[mid] === s) {
return mid;
}

if (nums[mid] > s) {
return binarySearch(nums, s, start, mid - 1);
}

if (nums[mid] < s) {
return binarySearch(nums, s, mid + 1, end);
}

return -1;
};
26 changes: 26 additions & 0 deletions HappyNumber/HappyNumber.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Some numbers are happy. Well they're only happy if sum of squares
* of their digits ends up as 1!
*/

function isHappy(n: number): boolean {
if (n == 1 || n == 7) return true;

let sum: number = n;

while (sum > 9) {
sum = sum
.toString()
.split('')
.map((digit) => {
return Number(digit);
})
.reduce((partialSum, a) => Math.pow(a, 2) + partialSum, 0);

if (sum == 1 || sum == 7) {
return true;
}
}

return false;
}
15 changes: 8 additions & 7 deletions HappyNumber/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,22 @@ 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.
- 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.

Example 1:

Input:<br> n = 19 <br>
<br>
Output:<br> true <br>
Example:
> *Input*: `n = 19`
<br>
Explanation: <br>
*Output:* `true`
<br>
*Explanation:* <br>
1<sup>2</sup> + 9<sup>2</sup> = 82 <br>
8<sup>2</sup> + 2<sup>2</sup> = 68 <br>
6<sup>2</sup> + 8<sup>2</sup> = 100 <br>
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1


## References

[1] [Check whether a number is happy](https://leetcode.com/problems/happy-number/)
[Happy Number LeetCode Problem](https://leetcode.com/problems/happy-number/)

[GeeksForGeeks Article on Happy Number](https://www.geeksforgeeks.org/happy-number/)