The following line in the swapDigits function below does not seem to work to convert the number a negative number.
swappedNumber = Number(numberStringArray.join("")) * -1;
If I multiply a positive number by -1 in the console it correctly makes the number negative but that does not seem to work in the code below. How can I make the swappedNumber negative? Thank you.
// swapDigits
const swapDigits = (number) => {
let swappedNumber = 0;
if (number < 0) {
number = Math.abs(number);
const numberString = number.toString();
console.log(numberString);
const numberStringArray = [];
if (numberString.length % 2 == 0) {
for (let i = 0; i < numberString.length; i = i + 2) {
numberStringArray.push(numberString[i + 1]);
numberStringArray.push(numberString[i]);
}
swappedNumber = Number(numberStringArray.join(""));
} else {
numberStringArray.push(numberString[0]);
for (let i = 1; i < numberString.length; i = i + 2) {
numberStringArray.push(numberString[i + 1]);
numberStringArray.push(numberString[i]);
}
swappedNumber = Number(numberStringArray.join("")) * -1;
}
} else {
const numberString = number.toString();
console.log(numberString);
const numberStringArray = [];
if (numberString.length % 2 == 0) {
for (let i = 0; i < numberString.length; i = i + 2) {
numberStringArray.push(numberString[i + 1]);
numberStringArray.push(numberString[i]);
}
swappedNumber = Number(numberStringArray.join(""));
} else {
numberStringArray.push(numberString[0]);
for (let i = 1; i < numberString.length; i = i + 2) {
numberStringArray.push(numberString[i + 1]);
numberStringArray.push(numberString[i]);
}
swappedNumber = Number(numberStringArray.join(""));
}
}
return swappedNumber;
};
const even = swapDigits(-564783);
console.log(even); // logs 657438 instead of -657438
const odd = swapDigits(512364783);
console.log(odd);
2
Answers
The first branch of your "if" doesn’t multiply the number by -1:
So if there’s an even number of digits, you won’t negate the number.
You can simplify your logic by capturing the sign, before calling absolute value.
You can also swap without a temporary variable by using an XOR swap.