While explaining the logic to my friends I found out that there is a little problem in it.
Logic given by @pavi2410 and later used by me too will not return correct value for 0 which makes mine and pavi solutions invalid and @WatermelonIce the real winner.