Javascript Interview Question String Convert Integer to String

Description

Javascript Interview Question String Convert Integer to String


function intToStr(num) {
}



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

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

    while (num !== 0) {
        temp.push(String.fromCharCode(zero + (num % 10)));
        num = Math.floor(num/10);
    }

    temp = temp.reverse();

    temp.splice(0, 0, isNegative ? '-' : '');

    return temp.join('');
}

console.log(intToStr(1234));
console.log(intToStr(-1234));



PreviousNext

Related