We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
We start off at some random prisoner S and try to distribute M candies. So we could just do S + M to see which prisoner we end up at. However, we may have more candies than prisoners, so we loop back around to the first prisoner by doing the % N where N is number of prisoners.
Each +1 and -1 that you see in the equation is to fix the off-by-one problems that exist since prisoners are counted from 1 to N while modular arithmetic is counted from 0.
Save the Prisoner!
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
From my HackerRank solutions.
We start off at some random prisoner S and try to distribute M candies. So we could just do S + M to see which prisoner we end up at. However, we may have more candies than prisoners, so we loop back around to the first prisoner by doing the % N where N is number of prisoners.
Each +1 and -1 that you see in the equation is to fix the off-by-one problems that exist since prisoners are counted from 1 to N while modular arithmetic is counted from 0.
Let me know if you have any questions.