diff --git a/DIRECTORY.md b/DIRECTORY.md index 3f34cc78..a86803d1 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -29,6 +29,7 @@ * [Is Even](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_even.ts) * [Is Leap Year](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_leap_year.ts) * [Is Odd](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_odd.ts) + * [Is Palindrome](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_palindrome.ts) * [Is Square Free](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_square_free.ts) * [Lowest Common Multiple](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/lowest_common_multiple.ts) * [Perfect Square](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/perfect_square.ts) diff --git a/maths/is_palindrome.ts b/maths/is_palindrome.ts new file mode 100644 index 00000000..f093d9be --- /dev/null +++ b/maths/is_palindrome.ts @@ -0,0 +1,21 @@ +/** + * A function to see if a number is a palindrome. + * Note that if the reversed number is larger than MAX_SAFE_INTEGER, rounding errors may occur and the result may be incorrect. + * Time Complexity: O(log(n)) + * + * @param number The input number. + * @return {boolean} Wether the number is a Palindrome or not. + */ +export const IsPalindrome = (number: number): boolean => { + if (number < 0 || (number % 10 === 0 && number !== 0)) { + return false; + } + + let reversed: number = 0; + while (number > reversed) { + reversed = reversed * 10 + (number % 10); + number = Math.floor(number / 10); + } + + return number === reversed || number === Math.floor(reversed / 10); +}; diff --git a/maths/test/is_palindrome.test.ts b/maths/test/is_palindrome.test.ts new file mode 100644 index 00000000..fa375f73 --- /dev/null +++ b/maths/test/is_palindrome.test.ts @@ -0,0 +1,10 @@ +import { IsPalindrome } from "../is_palindrome"; + +describe("IsPalindrome", () => { + test.each([[5, true], [1234, false], [12321, true], [31343, false]])( + "correct output for %i", + (nums, expected) => { + expect(IsPalindrome(nums)).toBe(expected); + }, + ); +}); \ No newline at end of file