From: dalke at bioreason.com (Andrew Dalke)
Date: Thu, 22 Apr 1999 13:07:50 -0600
Subject: Reversing Long integers
References: <371E0C46.E6FA76A9@princeton.edu>
Message-ID: <371F7386.92B1BB3C@bioreason.com>
X-UID: 1359                                                  

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




