add: 220504-CN [cpp]

This commit is contained in:
eat-swap 2022-05-04 18:35:52 +08:00
parent e56c314d02
commit 7f11d372ef
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 36 additions and 1 deletions

35
cpp/2205/220504-CN.cpp Normal file
View File

@ -0,0 +1,35 @@
#include <cstdio>
/**
* 1823. Find the Winner of the Circular Game
* There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.
*
* The rules of the game are as follows:
*
* Start at the 1st friend.
* Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.
* The last friend you counted leaves the circle and loses the game.
* If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.
* Else, the last friend in the circle wins the game.
* Given the number of friends, n, and an integer k, return the winner of the game.
*/
class Solution {
private:
static int helper(int n, int k) {
if (n <= 1)
return 0;
return (helper(n - 1, k) + k) % n;
}
public:
static int findTheWinner(int n, int k) {
if (k <= 1)
return n;
auto ans = (helper(n, k) + 1) % n;
return ans ? ans : n;
}
};
int main() {
std::printf("%d\n", Solution::findTheWinner(5, 2));
}

View File

@ -3,4 +3,4 @@ PROJECT(2205)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2204 220503.cpp) ADD_EXECUTABLE(2204 220504-CN.cpp)