GAZAR

Principal Engineer | Mentor

Reverse Integer Algorithm

Reverse Integer Algorithm

At its core, the Reverse Integer problem entails reversing the digits of a given integer while preserving its sign. For example, reversing 123 yields 321, while reversing -456 results in -654. The challenge lies in efficiently manipulating the digits of the integer to achieve the desired reversal.

const reverseInteger = (number) => {
    let oldNumber = number;
    let newNumber = 0;    
    while (oldNumber !== 0) {
      const singleDigit = oldNumber%10;      
      oldNumber = Math.  trunc(oldNumber/10)
      newNumber = newNumber*10 + singleDigit
    }
    return newNumber;
}

reverseInteger(123);
reverseInteger(-123);
Screenshot 2024-03-10 at 9.52.09 AM.png

The Reverse Integer algorithm may appear deceptively simple, but its implications extend far beyond the realm of algorithmic puzzles. By understanding its principles and applications, developers can appreciate its significance in problem-solving and algorithmic design. So, next time you encounter the Reverse Integer problem, embrace the challenge and let your coding prowess shine!