3

I am trying to get the output in this way, unfortunately, it isn't return expected value...

function reverseInt(int){
    let intRev ="";
    for(let i= 0; i<int.length; i++){
        intRev = int[i]+intRev ;
    }
    return intRev ;
}
console.log(reverseInt("-12345"));
Blue
  • 22,608
  • 7
  • 62
  • 92
phmollah
  • 33
  • 1
  • 3

11 Answers11

12

Use

function reverseInt(n) {
    return Math.sign(n)*parseInt(n.toString().split('').reverse().join(''));
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Jasmin Mistry
  • 1,459
  • 1
  • 18
  • 23
  • @JasminMistry Please don't ask for the green check mark when there other valid answers present. By the way, are you the one who downvoted my answer? – Tim Biegeleisen Aug 10 '18 at 06:20
4

Your basic logic is correct, but you need to handle the differences between positive and negative integer inputs. In the case of the latter, you want to start building the reversed string on the second character. Also, when returning the reversed negative number string, you need to also prepend a negative sign.

function reverseInt(int){
    let intRev = "";
    let start = int < 0 ? 1 : 0;
    for (let i=start; i<int.length; i++) {
        intRev = int[i] + intRev;
    }
    return int < 0 ? '-' + intRev : intRev;
}

console.log("12345 in reverse is:  " + reverseInt("12345"));
console.log("-12345 in reverse is: " + reverseInt("-12345"));

Edit: Some of the answers are making use of the base string reversing functions. But, this answer attemtps to fix the problems with your exact original approach.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Hope it will return the output you expected.

function reverseInt(int){
    const intRev = int.toString().split('').reverse().join('');
    return parseInt(intRev) * Math.sign(int);
}
alert(reverseInt("-12345"));
Maher Hossain
  • 192
  • 1
  • 10
1

If you want to use a purely mathematical solution, then it should be something like this:

Remove the last digit from the number and append it to the end of the reversed number variable until the original number is gone and the reversed number is complete.

Code:

var reverse = function(x) {
    let reverse = 0;
    let sign = Math.sign(x);
    if (sign === -1) {
        x = x*sign;
    }
    while (x > 0) {
        reverse = (reverse * 10) + (x%10);
        x = parseInt(x/10, 10);
    }
    return reverse * sign;
};
Malay
  • 635
  • 8
  • 11
  • I was looking for an answer that covered negative numbers without converting them to a string. This answer helped. Thank you :) – blossom-babs May 01 '22 at 05:03
0

function reverseInt(number){
    let intRev ="";
    let len=number.toString().length;
    for(let i=len i>0; i--){
        intRev =intRev + int[i];
    }
    return intRev;
}

This will give you the reverse of the number that you pass

Ramesh
  • 2,297
  • 2
  • 20
  • 42
0

Skip the minus sign and add it last to get something like -54321.

Example:

function reverseInt(int){
    let intRev ="";
    for(let i= 1; i<int.length; i++){
        intRev = int[i]+intRev ;
    }
    intRev ='-'+intRev;
    return intRev ;
}
console.log(reverseInt("-12345"));
alsace
  • 25
  • 6
0

A short little function that does the job :)

Enjoy

function reverseInt(int){
    const sign = int.match('-') ? '-' : '';
    return sign + Math.abs(int).toString().split('').reverse().join('');
}
console.log(reverseInt("-12345"));
Domenik Reitzner
  • 1,583
  • 1
  • 12
  • 21
0

This might be overkill however here is how I reverse an int.

Convert the arguments to a string, use the string reverse func and join the array. To check if the argument is positive or negative we check what is returned from Math.sign(). There are some shortcuts to convert the reverse item back to a int. This could be expanded to check if the int is 0 for example, it is not bullet proof. .

function reverse(int){
  let r = (Math.sign(int) > 0) ? +[...Array.from(int.toString()).reverse()].join('') : -Math.abs([...Array.from(int.toString()).reverse()].join('').replace('-',''));
  return r
}
console.log(reverse(-123))
dimButTries
  • 661
  • 7
  • 15
0

function reverseInt(n) {
    const isNegativeNumber = Boolean(n < 0)
    const reversedStringifiedNumber = n.toString().split('').reverse().join('')
    
    return parseInt(`${isNegativeNumber ? '-' : ''}${reversedStringifiedNumber}`)
}

console.log(reverseInt(1234))
console.log(reverseInt(-1234))
console.log(reverseInt(0))
console.log(reverseInt(-0))
Andy Coupe
  • 327
  • 2
  • 4
0

For negative/non-negative integers (not strings), this will work.

const reverseInteger = (int) => {
    let reversed = '';
    let sign = int < 0 ? 1 : 0;
    let convertIntToString = int.toString();
    for (let i = sign; i < convertIntToString.length; i++) {
        reversed = parseInt(convertIntToString[i] + reversed);
        //parseInt to convert to integer, doing this to mostly remove 
        //leading zeros
    }
    return int < 0 ? "-" + reversed : reversed;
};

console.log(reverseInteger(789));
console.log(reverseInteger(-51989000));
folake
  • 91
  • 1
  • 3
0

Here's a solution for positive and negative integers

function reverseInteger(num){
  let isNegative = false;
  let integerString = String(num)

  if (Math.sign(num) === -1) {
    isNegative = true;
    integerString = integerString.replaceAll("-", "");
  }

  const reversedStringArray = String(integerString).split("").reverse("");
  const result = reversedStringArray.toString().replaceAll(",", "");

  return isNegative ? Number(`-${result}`) : Number(result);
}