I could not understand what is the problem with the code , inspite of applying the right logic

Your code is not giving correct output.
For the Testcase -:
1
67
Output should be 55
But your code is giving 51

As there is no respond from your side. I am closing thr thread.