diff --git a/Binary Search/binary_search.ts b/Binary Search/binary_search.ts new file mode 100644 index 00000000..0a376e42 --- /dev/null +++ b/Binary Search/binary_search.ts @@ -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; +}; diff --git a/HappyNumber/HappyNumber.ts b/HappyNumber/HappyNumber.ts new file mode 100644 index 00000000..65872f4e --- /dev/null +++ b/HappyNumber/HappyNumber.ts @@ -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; +} \ No newline at end of file diff --git a/HappyNumber/Readme.md b/HappyNumber/Readme.md index 40bc0fee..10346302 100644 --- a/HappyNumber/Readme.md +++ b/HappyNumber/Readme.md @@ -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:
n = 19

-Output:
true
+Example: +> *Input*: `n = 19`
-Explanation:
+*Output:* `true` +
+*Explanation:*
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
-12 + 02 + 02 = 1 +12 + 02 + 02 = 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/) \ No newline at end of file