Skip to content

Latest commit

 

History

History
26 lines (22 loc) · 556 Bytes

8.string-to-integer-atoi.md

File metadata and controls

26 lines (22 loc) · 556 Bytes

字符串转换整数 (atoi)

题目

思路

通过String.prototype.trim去掉头尾空格, 通过正则匹配数值, 而后比较大小返回值即可

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
  str = str.trim()
  const match = str.match(/^[+-]?\d+/)
  const max = Math.pow(2, 31)
  if (match) {
    let num = Number(match[0])
    if (num >= max) num = max - 1
    if (num < 0 - max) num = 0 - max
    return num
  }
  return 0
};