admin管理员组

文章数量:1198811

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"));

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"));

The desired result is -54321, given the example above.

How do you reverse a string in-place? does not answer the question because the answers are dealing with characters and don't account for the negative sign.

Share Improve this question edited Oct 26, 2023 at 14:00 General Grievance 4,99837 gold badges37 silver badges55 bronze badges asked Aug 10, 2018 at 6:03 phmollahphmollah 411 silver badge3 bronze badges 0
Add a comment  | 

12 Answers 12

Reset to default 14

function reverseInt(n) {
        return Math.sign(n)*parseInt(n.toString().split('').reverse().join(''));
    }
    
console.log(reverseInt("-12345"));

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"));

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

function reverseInt(int){
    const intRev = int.toString().split('').reverse().join('');
    return parseInt(intRev) * Math.sign(int);
}
console.log(reverseInt("-12345")); // or alert(reverseInt("-12345"));

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;
};

const n = -315;
console.log(Math.sign(n) * Number(Math.abs(n).toString().split("").reverse().join(""))) ;

Here I used Math.sign which returns the sign of the number [-1,1] ; W and Math.abs returns the value without sign. To reverse the number > string > array > reverse > string > number

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

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"));

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"));

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))

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))

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));

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);
}

本文标签: javascriptHow to reverse the digits on a negative numberStack Overflow