Reverse Integer in Javascript


  • 0
    D

    Here is my simple solution for this problem. Basically, we need to check whether the number is greater than 2147483647 and return 0 for it.

    var reverse = function(x) {
        var result = x.toString().split("").reverse().join("")
        var signed = ""
        for (var i = 0; i < result.length; i++){
            if (result[i] == "-"){
                signed = "-"
                if (parseInt(result, 10) >= 2147483647){
                    return 0
                }
                else {
                    return parseInt(signed + parseInt(result))
                }
            }
            else {
                if (parseInt(result, 10) >= 2147483647){
                    return 0
                }
            }
        }
        if( signed != "-") {
            result = parseInt(result)
            return result
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.