From 304866ecbfbcd0aa83511e159c993341d54d9d65 Mon Sep 17 00:00:00 2001 From: yige Date: Sun, 10 May 2020 16:13:38 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E5=9B=9E=E6=96=87=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ src/math/palindrome-number.js | 16 ++++++++++++++++ test/math/palindrome-number.test.js | 9 +++++++++ 3 files changed, 30 insertions(+) create mode 100644 src/math/palindrome-number.js create mode 100644 test/math/palindrome-number.test.js diff --git a/README.md b/README.md index f9d24c5..b61603c 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 面试题 16.07. 最大数值 https://leetcode-cn.com/problems/maximum-lcci/ +- [回文数](src/math/palindrome-number.js) + + - LeetCode 9. 回文数 https://leetcode-cn.com/problems/palindrome-number/ + - LintCode 491. 回文数 https://www.lintcode.com/problem/palindrome-number/ + ## 堆 - [超级丑数](src/stack/super-ugly-number.js)【未完成】 diff --git a/src/math/palindrome-number.js b/src/math/palindrome-number.js new file mode 100644 index 0000000..e0707dd --- /dev/null +++ b/src/math/palindrome-number.js @@ -0,0 +1,16 @@ +/** + * @param {number} x + * @return {boolean} + */ +export const isPalindrome = function (x) { + if (x < 0 || (x % 10 === 0 && x !== 0)) return false // 如果末尾数为0且不是0 + + let reverse = 0 + + while (reverse < x) { + reverse = reverse * 10 + x % 10 + x = x / 10 | 0 + } + + return reverse === x || (reverse / 10 | 0) === x +} diff --git a/test/math/palindrome-number.test.js b/test/math/palindrome-number.test.js new file mode 100644 index 0000000..c5fe474 --- /dev/null +++ b/test/math/palindrome-number.test.js @@ -0,0 +1,9 @@ +import { isPalindrome } from '../../src/math/palindrome-number' + +test('回文数', () => { + expect(isPalindrome(121)).toBe(true) + expect(isPalindrome(0)).toBe(true) + expect(isPalindrome(11)).toBe(true) + expect(isPalindrome(10)).toBe(false) + expect(isPalindrome(-121)).toBe(false) +})