Reverse an Integer - via JavaScript

Reverse an Integer - via JavaScript

Introduction

  • This is the 3rd post in the series DS and Algo Practice - using examples and snippets.
  • We would leverage our previous string reversal techniques to reverse and return back an integer.

Problem Statement

  • Reverse an integer, preserve the negative sign if it exists, remove the facing zeros, if they exist.
  • For ex: 3000 would be reversed to 3 -> facing zeros need to be removed.
  • -90091 would be reversed to -19009 -> negative sign needs to be persisted.

Implementations

1) A crude implementation

Input Integer -> Convert to String Array -> Search for negative sign -> Reverse the string -> Append the negative sign if the search yields true -> Convert the reversed string back to the integer.

function reverseInt(number) {
  if (!number || isNaN(number)) {
    return "Invalid format - input is not a integer";
  }
  let strArray = number.toString().split("");
  let isNegative = strArray.indexOf("-") !== -1 ? true : false;
  let reversedStr = strArray.reverse().join("");
  reversedStr = isNegative ? `${"-"}${reversedStr}` : reversedStr;
  return parseInt(reversedStr);
}

console.log(reverseInt(123));
console.log(reverseInt(-981));
console.log(reverseInt(500));
console.log(reverseInt(-900));
console.log(reverseInt(-900123));
console.log(reverseInt(""));
console.log(reverseInt("hello world"));
console.log(reverseInt(null));
console.log(reverseInt(NaN));

image.png

2) Using Math.sign(num) method.

Math.sign(num) method returns +1/-1 depending upon the passed in number.

This method simplifies the above implementation.

Input Integer -> Convert to String Array and Reverse it -> Parse the reversed string back to Integer -> Multiply the reversed integer with Math.sign(Input Integer)

//Alternate approach using Math.sign() method
function reverseIntAlternate(number) {
  if (!number || isNaN(number)) {
    return "Invalid format - input is not a integer";
  }

  let reversedNumber = parseInt(number.toString().split("").reverse().join(""));

  return reversedNumber * Math.sign(number);
}

console.log(reverseIntAlternate(123));
console.log(reverseIntAlternate(-981));
console.log(reverseIntAlternate(500));
console.log(reverseIntAlternate(-900));
console.log(reverseIntAlternate(-900123));
console.log(reverseIntAlternate(""));
console.log(reverseIntAlternate("hello world"));
console.log(reverseIntAlternate(null));
console.log(reverseIntAlternate(NaN));

image.png

Code is available at - github.com/anurag1302/dsalgo-javascript/blo..

Did you find this article valuable?

Support TechnCode by becoming a sponsor. Any amount is appreciated!