DEV Community

tommy-3
tommy-3

Posted on

Learning Algorithms with JS, Python and Java 3: Integer Reversal

I joined dev.to this week and posted two little articles. Thank you for the hearts and unicorns (though I'm still not really sure what unicorns mean)!

The third question in the Stephen Grider's course is to reverse an integer. I'll just quote the directions here.

--- Directions
Given an integer, return an integer that is the reverse ordering of numbers.
--- Examples
reverseInt(15) === 51
reverseInt(981) === 189
reverseInt(500) === 5
reverseInt(-15) === -51
reverseInt(-90) === -9

Stephen's JS solution is:

function reverseInt(n) {
    const reversed = n
        .toString()
        .split('')
        .reverse()
        .join('');

    return parseInt(reversed) * Math.sign(n);
}
Enter fullscreen mode Exit fullscreen mode

This works because parseInt('12-') returns 12.

A neater solution might be:

function reverseInt(n) {
    const absReversed = Math.abs(n)
        .toString()
        .split('')
        .reverse()
        .join('');

    return Number(absReversed) * Math.sign(n);
}
Enter fullscreen mode Exit fullscreen mode

My attempt in Python:

def reverse_int(n):
    abs_reversed = str(abs(n))[::-1]
    if n > 0:
        return int(abs_reversed)
    else:
        return -int(abs_reversed)
Enter fullscreen mode Exit fullscreen mode

int('12-') throws a ValueError, so abs() cannot be omitted.
I wonder if there's a cooler way to do it.

And Java:

public static int reverseInt(int n) {
    String abs = Integer.toString(Math.abs(n));
    String absReversed = new StringBuilder(abs).reverse().toString();
    return Integer.parseInt(absReversed) * Integer.signum(n);
}
Enter fullscreen mode Exit fullscreen mode

parseInt('12-') throws a NumberFormatException in Java, so Math.abs() cannot be omitted.

Top comments (1)

Collapse
 
pbouillon profile image
Pierre Bouillon • Edited

May I suggest for Python:

def reverse_int(n: int) -> int:
    return int(str(n)[::-1]) if n >= 0 else -int(str(n)[1:][::-1])

A little bit more concise:

  • if the number is positive, I reverse it as a string and return it as an integer
  • if the number is negative, I do the same method but without looking at the first char (-), then I return it as a negative integer (which is exactly like your method) The advantage is that you can "convert" both positive and negative numbers !

examples:

import sys


if __name__ == '__main__':
    print(reverse_int(12))            # 21
    print(reverse_int(-12))           # -21
    print(reverse_int(0))             # 0
    print(reverse_int(sys.maxsize))   # 7085774586302733229
    print(reverse_int(-sys.maxsize))  # -7085774586302733229

Also, if you want to go deeper and converting both integer and float, you could use something like this !

from typing import Any


def reverse_all(n: Any) -> Any:
    return type(n)(str(n)[::-1]) if n >= 0 else -type(n)(str(n)[1:][::-1])

Which allows:

if __name__ == '__main__':
    print(reverse_all(41.3))   # 3.14
    print(reverse_all(-41.3))  # -3.14
    print(reverse_all(-12))    # -21
    print(reverse_all(12))     # 21