Reverse Integer (signed 32-bit integer)

I want to know how to reverse the order of the numbers, yet keep the minus sign(-) at its place. See the code below to get what i mean.

The idea this challenge is to reverse the number, and then to check if the reversed version of the number is less than -2 ^ 31 or if it’s bigger than 2 ^ 31 - 1. Then i should return 0, otherwise, i should return the reversed version of the number.

const reverse = x => {
const array = x.toString().split("");
const newArray = [];

for (let B = array.length - 1; B >= 0; B = B - 1) {
if (typeof array[B] === "number") {
  newArray.push(array[B]);
  return newArray;
} else {
  array[B];
}}
};
 
// the numbers in the comments are the desired result.
console.log(reverse(0)); // 0
console.log(reverse(120)); // 21
console.log(reverse(123)); // 321
console.log(reverse(-123)); // -321
console.log(reverse(1534236469)); // 0

Hello:

Try after the loop:
if !isNaN(array[B])
instead of
typeof()
because the latter will always return a string after check, never a number.

(This is one of those brain-twisting boolean logics: You are checking if it’s not not a number.)

Handle the negative sign in another if check and then use return:
If x < 0 use return -parseInt() on the new array (this will turn the result negative)
else return parseInt()
Parse newArray.join(‘’) in both cases

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.