c#, java, javascript


  • 0
    C

    c#

    public int Reverse(int x)
    {
        int sign = Math.Sign(x);
    
        var digits = new List<int>();
    
        while (x != 0)
        {
            int digit = x % 10;
            x -= digit;
            x /= 10;
            digits.Add(digit);
        }
    
        int count = digits.Count;
    
        double result = 0;
        for (int i = 0; i < count; ++i)
            result += Math.Pow(10, count - i - 1) * digits[i];
    
        result = Math.Abs(result);
    
        return result > int.MaxValue
            ? 0
            : sign * (int)result;
    }
    

    java

    public int reverse(int x) {
        double sign = Math.signum(x);
    
        List<Integer> digits = new ArrayList<Integer>();
    
        while (x != 0)
        {
            int digit = x % 10;
            x -= digit;
            x /= 10;
            digits.add(digit);
        }
    
        int count = digits.size();
    
        double result = 0;
        for (int i = 0; i < count; ++i)
            result += Math.pow(10, count - i - 1) * digits.get(i);
    
        result = Math.abs(result);
    
        return result > Integer.MAX_VALUE
                ? 0
                : (int)(sign * result);
    }
    

    javascript

    var reverse = function(x) {
        let sign = Math.sign(x);
        let digits = [];
    
        while (x !== 0)
        {
            let digit = x % 10;
            x -= digit;
            x /= 10;
            digits.push(digit);
        }
    
        let count = digits.length;
    
        let result = 0;
        for (let i = 0; i < count; ++i)
            result += Math.pow(10, count - i - 1) * digits[i];
    
        result = Math.abs(result);
    
        return result > Math.pow(2, 31)
                    ? 0
                    : sign * result;
    };
    

Log in to reply
 

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