Thursday, July 07, 2016

reverse an integer

This works for -ve ints too (as -9 % 10 = -9). checked to throw overflow ex for int 1000000009.
(n):
    checked:
        nrev = 0
        while n != 0:
            nrev = nrev *10 + (n %10)
            n = n /10
        return nrev
[Hat tip to S]

No comments:

Post a Comment