HCL Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
Idea:
let n = 123456
Note that:
- There are ceil(log10 n) = 6 digits in '123456'
- floor(n / pow(10, ceil(log10 n) - 1)) = 1 (i.e. 123456 / 10000 = 1.23456 -> 1)
- n % 10 (i.e. 123456 % 10 = 6)
Putting this all together (Python):
int(( math.pow(10, 6-1) * (n % 10) + n % math.pow(10, 6-1) ) - (n % 10) + math.floor(n / math.pow(10, 6-1) )) = 623451
Rinse and repeat for the rest of the digits, and you should be able to flip it in place.
(I sure hope there's a better way than this!)
hmm without using temp it would definitely have to be recursive way
anyway here the solution with temp variables (in python)
>>> sum = 0
>>> num = 123
>>> while num:
elem = num % 10
sum = sum*10 + elem
num = num // 10
unfortunately even with recursion i had to use a extra variable .. wonder if that s allowed
>>> def reverse(num,sum):
if num == 0 :
return sum
return reverse(num//10,sum*10+num%10)
>>> reverse(123,0)
>>> 321
- Anonymous April 14, 2013