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 calculate the index of the prisoner to warn using the formula (m - 1 + s - 1) % n + 1.
(m - 1) calculates the position of the last candy.
+ s - 1 calculates the starting position of distribution.
% n handles the circular nature of the distribution, ensuring the index remains within the range of 1 to n.
+ 1 adjusts the index to match the numbering of chairs (which starts from 1).
If the calculated index is 0, it means it's the last chair, so we set it to n to match the numbering of chairs.
publicstaticintsaveThePrisoner(intn,intm,ints){// Calculate the index of the prisoner to warnintindex=(m-1+s-1)%n+1;// If the index is 0, set it to n (since the prisoners are seated around a circular table)if(index==0){index=n;}
return index;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Save the Prisoner!
You are viewing a single comment's thread. Return to all comments →
We calculate the index of the prisoner to warn using the formula (m - 1 + s - 1) % n + 1. (m - 1) calculates the position of the last candy. + s - 1 calculates the starting position of distribution. % n handles the circular nature of the distribution, ensuring the index remains within the range of 1 to n. + 1 adjusts the index to match the numbering of chairs (which starts from 1). If the calculated index is 0, it means it's the last chair, so we set it to n to match the numbering of chairs.
}