Created
June 18, 2023 17:09
-
-
Save amitkbiswas01/b1fa20bee7e5dfa98a31215e72b3cea8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// problem 1 | |
function isPalindrome(x: number): boolean { | |
const xStr = x.toString(); | |
for (let index = 0; index < xStr.length / 2; index++) { | |
const leftIndex = index; | |
const rightIndex = xStr.length - index - 1; | |
if (leftIndex === rightIndex) return true; | |
if (xStr[leftIndex] !== xStr[rightIndex]) return false; | |
} | |
return true; | |
} | |
// console.log(isPalindrome(121)); | |
// console.log(isPalindrome(-121)); | |
// console.log(isPalindrome(10)); | |
// problem 3 | |
function reverseDigit(given: number) { | |
const reverseStr = given.toString().split("").reverse().join(""); | |
let zeroEndsAt = -999; | |
for (let index = 0; index < reverseStr.length; index++) { | |
if (parseInt(reverseStr[index]) > 0) { | |
zeroEndsAt = index; | |
break; | |
} | |
} | |
return parseInt(reverseStr.split("").slice(zeroEndsAt).join("")); | |
} | |
function distinctPositive(arr: number[]): number { | |
const result = [...arr]; | |
for (const num of arr) { | |
result.push(reverseDigit(num)); | |
} | |
const distinct = {}; | |
for (const num of result) { | |
if (distinct[num]) continue; | |
distinct[num] = true; | |
} | |
return Object.keys(distinct).length; | |
} | |
// console.log(distinctPositive([1, 13, 10, 12, 31])); | |
// console.log(distinctPositive([13, 13, 12, 12, 31])); | |
// console.log(distinctPositive([2, 2, 2])); | |
// problem 2 | |
function distinctTriplets(arr: number[]) { | |
const triplets: number[][] = []; | |
for (let i = 0; i < arr.length; i++) { | |
for (let j = 0; j < arr.length; j++) { | |
for (let k = 0; k < arr.length; k++) { | |
if (i != j && j != k && i != k && arr[i] + arr[j] + arr[k] === 0) { | |
triplets.push([arr[i], arr[j], arr[k]]); | |
} | |
} | |
} | |
} | |
// some function to find distinct triplets to find in triplets array | |
// hashmap or set can be used | |
const map = {}; | |
for (const triplet of triplets) { | |
console.log(triplet); | |
} | |
return triplets; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment