1. 程式人生 > >leetcode-8. 字串轉整數 (atoi)

leetcode-8. 字串轉整數 (atoi)

/**
 * @param {string} str
 * @return {number}
 */
var myAtoi = function(str) {
    let max = Math.pow(2,31)-1;
    let min = -max-1;
    let reg = /^\s*([-+]?\d+).*$/igm;
    let arr = reg.exec(str);
    if(arr == null || arr[1] == null){
        return 0;
    }
    let res = +arr[1];
    if(res>max){
        return max;
    }else if(res<min){
        return min;
    }else{
        return res;
    }
};