Thursday, January 23, 2014

given an integer, find the closest number that is palindrome ??????????????

Q:
Given a base 10 number N, find the nearest palindromic base 10 number X to N. If N is already palindromic do nothing.
If two palindromic numbers are equidistant to N, (10 - 1 = 9, 10 + 1 = 11) returning either is acceptable.

A:


The logic can work as below .

1)Increment the mid number

2)If mid number ==9 , after incrementing , make it zero and go to the next number to the left of it i.e. mid-1

repeat the above procedure for mid-1 element

If you reach the least number i.e. the first digit and it is also 9 , make it zero and add 1 to the left of it

The procedure is continued till we reach a number which does not have a nine or we reach the left most digit

this will do

e.g

1991

middle no is 9 . make to 0 and go to the number left to it

1991==>1091

now we check 1 , increment it to 2

1091==>2091 . we reached a non-nine number , hence we stop .

now reflect it .

2091==2002 , done

in another case

999

increment middle and go to right , we have

909 , do the same again

as we are on the leftmost digit and it is also 9 , make it 0and add an extra 1 to the left

909==1009

now reflect it

1009==1001

This approach will work , as this is a problem on spoj as well

1 comment: