Skip to content

8. 字符串转换整数 (atoi)

8. 字符串转换整数 (atoi)

代码

javascript
// 8. 字符串转换整数 (atoi):https://leetcode.cn/problems/string-to-integer-atoi/
// 输入:" -042"
// 输出:-42

export function stringToIntegerAtoi (s) {
  let res = 0
  let sign = 1
  let i = 0
  const len = s.length
  while (i < len && s[i] === ' ') {
    i++
  }
  if (i < len && s[i] === '-') {
    sign = -1
    i++
  }
  if (i < len && s[i] === '+') {
    if (sign === -1) return 0
    i++
  }
  while (i < len && s[i] >= '0' && s[i] <= '9') {
    res = res * 10 + Number(s[i])
    i++
  }
  res = res * sign
  const intMax = 2 ** 31 - 1
  if (res > intMax) {
    return intMax
  }
  const intMin = -(2 ** 31)
  if (res < intMin) {
    return intMin
  }
  return res
}
typescript
// 8. 字符串转换整数 (atoi):https://leetcode.cn/problems/string-to-integer-atoi/
// 输入:" -042"
// 输出:-42

export function stringToIntegerAtoi (s: string): number {
  let res = 0
  let sign = 1
  let i = 0
  const len = s.length
  while (i < len && s[i] === ' ') {
    i++
  }
  if (i < len && s[i] === '-') {
    sign = -1
    i++
  }
  if (i < len && s[i] === '+') {
    if (sign === -1) return 0
    i++
  }
  while (i < len && s[i] >= '0' && s[i] <= '9') {
    res = res * 10 + Number(s[i])
    i++
  }
  res = res * sign
  const intMax = 2 ** 31 - 1
  if (res > intMax) {
    return intMax
  }
  const intMin = -(2 ** 31)
  if (res < intMin) {
    return intMin
  }
  return res
}

测试代码

ts
import { expect, test } from 'vitest'
import { stringToIntegerAtoi } from './typescript.ts'
import { stringToIntegerAtoi as stringToIntegerAtoiJs } from './javascript.js'

test(`stringToIntegerAtoi`, () => {
  expect(stringToIntegerAtoi('42')).toBe(42)
  expect(stringToIntegerAtoi(' -042')).toBe(-42)
  expect(stringToIntegerAtoi('1337c0d3')).toBe(1337)
  expect(stringToIntegerAtoi('0-1')).toBe(0)
  expect(stringToIntegerAtoi('words and 987')).toBe(0)
  expect(stringToIntegerAtoi('-+12')).toBe(0)
  expect(stringToIntegerAtoi('+12')).toBe(12)
})

test(`stringToIntegerAtoiJs`, () => {
  expect(stringToIntegerAtoiJs('42')).toBe(42)
  expect(stringToIntegerAtoiJs(' -042')).toBe(-42)
  expect(stringToIntegerAtoiJs('1337c0d3')).toBe(1337)
  expect(stringToIntegerAtoiJs('0-1')).toBe(0)
  expect(stringToIntegerAtoiJs('words and 987')).toBe(0)
  expect(stringToIntegerAtoiJs('-+12')).toBe(0)
  expect(stringToIntegerAtoiJs('+12')).toBe(12)
})