Reverse decimal digits in javascript

后端 未结 14 918
灰色年华
灰色年华 2021-02-05 16:24

How do I reverse the digits of a number using bitwise?

input:

x = 123; 

output:

x = 321; 
14条回答
  •  逝去的感伤
    2021-02-05 16:58

    Here are reversible array functions in JavaScript that handle integers or strings:

    function reverse(array)
    {
        var left = null;
        var right = null;
        var length = array.length;
        for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
        {
            var temporary = array[left];
            array[left] = array[right];
            array[right] = temporary;
        }
        return array;
    }
    
    function toDigitsArrayFromInteger(integer, isReverse)
    {
        var digits = [];
    
        if (integer > 0)
        {
            var floor = window.Math.floor;
            while (integer > 0)
            {
                digits.push(floor(integer % 10));
                integer = floor(integer / 10);
            }
    
            // Array is populated in reverse order. Un-reverse it to make it normal.
            if (!isReverse)
            {
                digits = reverse(digits);
            }
        }
        else if (integer < 0)
        {
            digits = toDigitsArrayFromInteger(-integer, isReverse);
        }
        else if (integer === 0)
        {
            digits.push(0);
        }
    
        return digits;
    }
    
    function toDigitsArrayFromString(string, isReverse)
    {
        var digits = [];
    
        string += ""; // Coerce to string.
    
        var i = null;
        var length = string.length;
        for (i = 0; i < length; i += 1)
        {
            var integer = parseInt(string.charAt(i), 10);
            if (isFinite(integer))
            {
                digits.push(integer);
            }
        }
    
        if (isReverse)
        {
            digits = reverse(digits);
        }
    
        return digits;
    }
    

    Once you have the digits as an array, you can reverse the array easily to get the digits starting from the left or from the right.

    The string function is more versatile because it can find any digit in a string, whereas the integer function is limited to integers.

    Benchmarks: http://jsperf.com/todigitsarray

    The benchmarks between the two functions show that in Firefox 10 and Chrome 12, the string function is 30% to 60% faster than the integer function. In Opera 12, the integer function is slightly faster by about 10%.

提交回复
热议问题