Reversing Long integers

Andrew Dalke dalke at bioreason.com
Thu Apr 22 15:07:50 EDT 1999


Ira H. Fuchs wrote:
> Can anyone think of a particularly clever way to [add a [long]
> integer to its reverse]

Nothing cleverer than

import string
def add_reverse(n):
  x = map(None, str(long(n))[:-1])
  x.reverse()
  return n + long(string.join(x,''))


>>> add_reverse(11111111111111L)
22222222222222L
>>> add_reverse(11111111111119L)
102222222222230L
>>> add_reverse(876437643654354239321L)
1000370097110700973999L


The long(n) is to enforce that the L exists as otherwise this won't
work for regular integers.


> the loop must include moving the L to the end of the reversed string
> prior to summing.

No need, long("123456789123487") == 123456789123487L .

						Andrew
						dalke at acm.org




More information about the Python-list mailing list