Reverse digits of an integer. - Javascript Number Operation

Javascript examples for Number Operation:Number Algorithm

Description

Reverse digits of an integer.

Demo Code


/*//w  w  w .j  av  a  2s  .c om
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321
*/
function reverse(x) {
  let symb;
  let arr = x.toString().split('');

  if(arr[0] === '-' || arr[0] === '+') {
    symb = arr[0];
    arr.shift();
    arr = parseInt(symb + arr.reverse().join(''));
  } else {
      arr = parseInt(arr.reverse().join(''));
    }
  let length = ((arr >> 0).toString(2).length);

  console.log((arr >> 0).toString(2))

  if(length >= 32) {
    return 0;
  } else {
    return arr;
    }
}

Related Tutorials