def rev(val): if val < 10: return val else: expon = int(math.log10(val)) ival = val%10 dval = val/10 return int(ival*math.pow(10,expon)) + rev(dval)
But today i tryed to make another, shorter solution. It has nothing todo with math. Actually i just take an int variable, convert it into string, reverse it, and convert it back into int. Really simple and it also works flawless:
def strrev(sval): if len(str(sval)) == 1: return sval else: strcon = str(sval) return int(strcon[::-1])
Now i'm wondering which function would be better and for what reason. I made some benchmarks and found out that the second solution is about 25% faster than the first one, but i just stoped these two version with "time". I think it's not good enough to take is as a benchmark. Besides that, i don't know anything about memory consumption. Anyway, i'll keep the second, since it's faster...
If someone wants to try it out, i've uploaded both "benchmark" script's. The scirpt generates every number from 1 to 100000, reverses every number and subtracts every number with it's reversed version.