NC100 字符串转换成整数

177 阅读1分钟

image.png

image.png

/**
 *
 * @param str string字符串
 * @return int整型
 */
function atoi(str) {
  // write code here
  const MAX_VALUE = 2 ** 31 - 1
  const MIN_VALUE = -(2 ** 31)
  const digits = '0123456789'
  let result = 0
  let sign = 1
  let i = 0

  // 逐个读取数字字符并转换为整数
  while (i < str.length && digits.includes(str[i])) {
    const digit = parseInt(str[i])

    // 检查结果是否超过边界值
    if (result > Math.floor(MAX_VALUE / 10) || (result === Math.floor(MAX_VALUE / 10) && digit > MAX_VALUE % 10)) {
      // 超出范围取最大值或者最小值
      return sign === 1 ? MAX_VALUE : MIN_VALUE
    }

    result = result * 10 + digit
    i++
  }

  return sign * result
}
module.exports = {
  atoi: atoi,
}

将字符串转化为整数_牛客题霸_牛客网 (nowcoder.com)