You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function getMostNumber(str){
let reg = /^[+-]?[0-9]*/
str = str.trimStart()
let temp =str.match(reg)
console.log(reg.exec(str),str.match(reg),temp,'temp')
let max =Math.pow(2,31)
let min = -max-1
if(temp<min){
return min
}
if(temp>max){
return max
}
if(!temp){
return 0
}
return temp[0]
}
console.log(getMostNumber('42'))
console.log(getMostNumber(" -42"))
console.log(getMostNumber("4193 with words"))
console.log(getMostNumber("words and 987"))
console.log(getMostNumber("-91283472332"))
Activity
violetrosez commentedon Nov 27, 2020
暴力api
sisterAn commentedon Nov 29, 2020
解答:parseInt
而题目的主要规则可以概况为:
32位内0所有的条件
parseInt都满足,除了32位内(含)parseInt返回的是NaN代码实现:
非 parseInt 解答:
sunsmeil commentedon Dec 1, 2020
fxwing commentedon Dec 7, 2020
JohnApache commentedon Apr 28, 2021
没有使用Js自带的
parseIntapi, 实现了效果BlueOrgreen commentedon Oct 30, 2021
const atoi = (str) => {
const trimStr = str.replace(/(^\s*)|(\s*$)/g, '')
if(!/^[\d|-]/g.test(trimStr)) return 0
const matchStr = /(-)?\d+/g.exec(trimStr)
const result = parseInt(matchStr)
if(result < 0 && result < -(2 ** 31)) return 'INT_MIN (−231)'
if(result > 0 && result > 2 ** 31 - 1) return 'INT_MAX (231 − 1)'
return parseInt(matchStr)
}
AlexZhang11 commentedon May 31, 2024
function getMostNumber(str){ let reg = /^[+-]?[0-9]*/ str = str.trimStart() let temp =str.match(reg) console.log(reg.exec(str),str.match(reg),temp,'temp') let max =Math.pow(2,31) let min = -max-1 if(temp<min){ return min } if(temp>max){ return max } if(!temp){ return 0 } return temp[0] } console.log(getMostNumber('42')) console.log(getMostNumber(" -42")) console.log(getMostNumber("4193 with words")) console.log(getMostNumber("words and 987")) console.log(getMostNumber("-91283472332"))