Javascript Interview Question String Convert String to Integer

Description

Javascript Interview Question String Convert String to Integer

function strToInt(str) {
    
}



/**
 * @function {public static} strToInt
 *
 * Converts a given `String` to an `Integer`.
 *
 * @param {String} str - the `String` to convert.
 *
 * @return the converted `Integer`.
 */
function strToInt(str) {
    var i = 0;
    var num = 0;
    var len = str.length;
    var isNegative = false;
    var zero = '0'.charCodeAt(0);

    if (str[0] === '-') {
        isNegative = true;
        i = 1;
    }

    while (i < len) {
        num *= 10;
        num += str.charCodeAt(i++) - zero;
    }

    if (isNegative) {
        num *= -1;
    }

    return num;
}

console.log(strToInt('1234'));
console.log(strToInt('-1234'));



PreviousNext

Related