leetcode 7. Reverse Integer

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    if (x == 0) {
        return x;
    }
    var negative = false;
    if (x < 0) {
        negative = true;
    }
    var num = x + '';
    if (num[0] == '-' || num[0] == '+') {
        num = num.substring(1);
    }
    var ret = reverseStr(num);
    //console.log(ret);
    var retNum = parseInt(ret);
    if (negative) {
        retNum = -retNum;
    }
    if (retNum > 2147483647 || retNum < -2147483648) {   // [2^31, 2^31 - 1]
        return 0;
    }
    return retNum;
};

var reverseStr = function(seq) {
    var s = 0;
    var e = seq.length - 1;
    var ret = new Array(seq.length);
    while (s <= e) {
        //var temp = seq[s];
        ret[s] = seq[e];
        ret[e] = seq[s];
        s++;
        e--;
    }
    return ret.join('');
};

你可能感兴趣的:(leetcode 7. Reverse Integer)