add: 回文数
This commit is contained in:
parent
da0e4f1359
commit
304866ecbf
@ -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)【未完成】
|
||||
|
16
src/math/palindrome-number.js
Normal file
16
src/math/palindrome-number.js
Normal 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
|
||||
}
|
9
test/math/palindrome-number.test.js
Normal file
9
test/math/palindrome-number.test.js
Normal 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)
|
||||
})
|
Loading…
Reference in New Issue
Block a user