7. 整数反转
代码
javascript
// 输入:x = 123
// 输出:321
export function reverse(x) {
let res = 0
while (x !== 0) {
res = res * 10 + x % 10
x = ~~(x / 10)
const max = Math.pow(2, 31)
if (res < -max || res > max - 1) return 0
}
return res
}
typescript
// 输入:x = 123
// 输出:321
export function reverse(x: number): number {
let res = 0
while (x !== 0) {
res = res * 10 + x % 10
x = ~~(x / 10)
const max = Math.pow(2, 31)
if (res < -max || res > max - 1) return 0
}
return res
}
测试代码
ts
import { expect, test } from 'vitest'
import { reverse } from './typescript.ts'
import { reverse as reverseJs } from './javascript.js'
test(`123`, () => {
expect(reverse(123)).toBe(321)
})
test(`123`, () => {
expect(reverseJs(123)).toBe(321)
})