DEV Community

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

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