Skip to content

Latest commit

 

History

History
45 lines (37 loc) · 849 Bytes

7.整数反转.md

File metadata and controls

45 lines (37 loc) · 849 Bytes

7.整数反转

/*
 * @lc app=leetcode.cn id=7 lang=typescript
 *
 * [7] 整数反转
 */

// @lc code=start
function reverse(x: number): number {}
// @lc code=end

解法 1: 转成字符串

function reverse(x: number): number {
  const sign = x < 0 ? -1 : 1
  x = x * sign
  const n = (x + '').length
  let res = 0
  for (let i = 1; i < n + 1; i++) {
    res = res * 10 + Math.floor((x % Math.pow(10, i)) / Math.pow(10, i - 1))

    if (res > Math.pow(2, 31) - 1) return 0
  }

  return res * sign
}

Case

test.each([
  { input: { x: 123 }, output: 321 },
  { input: { x: -123 }, output: -321 },
  { input: { x: 120 }, output: 21 },
  { input: { x: 0 }, output: 0 },
  { input: { x: 1534236469 }, output: 0 },
])('input: x = $input.x', ({ input: { x }, output }) => {
  expect(reverse(x)).toEqual(output)
})