add: 回文数

This commit is contained in:
yi-ge 2020-05-10 16:13:38 +08:00
parent da0e4f1359
commit 304866ecbf
3 changed files with 30 additions and 0 deletions

View File

@ -299,6 +299,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 面试题 16.07. 最大数值 https://leetcode-cn.com/problems/maximum-lcci/ - 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)【未完成】 - [超级丑数](src/stack/super-ugly-number.js)【未完成】

View File

@ -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
}

View File

@ -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)
})