9. 回文数
代码
javascript
// 输入:x = 121
// 输出:true
export function isPalindrome(x) {
if (x < 0) return false
let num = x
let res = 0
while (num !== 0) {
res = res * 10 + num % 10
num = ~~(num / 10)
}
return res === x
}
typescript
// 输入:x = 121
// 输出:true
export function isPalindrome(x: number): boolean {
if (x < 0) return false
let num = x
let res = 0
while (num !== 0) {
res = res * 10 + num % 10
num = ~~(num / 10)
}
return res === x
}
测试代码
ts
import { expect, test } from 'vitest'
import { isPalindrome } from './typescript.ts'
import { isPalindrome as isPalindromeJs } from './javascript.js'
test(`121`, () => {
expect(isPalindrome(121)).toEqual(true)
})
test(`121`, () => {
expect(isPalindromeJs(121)).toEqual(true)
})