faqts : Computers : Programming : Languages : Python : Snippets : Maths

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 2 people (50%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

Reversing long integers

Jul 5th, 2000 09:59
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 90, Andrew Dalke


"""
Packages: maths
"""
"""
> 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,''))
print add_reverse(11111111111111L)
#22222222222222L
print add_reverse(11111111111119L)
#102222222222230L
print 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 .
"""