Ganesha's patter

Even after unlocking the editorial i am not able to understand the answer as its written in c++ and even the logic is not at all clear
so please give detailed solution with steps,

Hi Vaibhav

The editorial is quite self explanatory.
The code is Java will be uploaded soon. But it is quite clearly explained in the code. The logic is exactly similar.
Ping me in case you still face error.