From 7f11d372efc694acd6e17dfbe5b90d4a284d039f Mon Sep 17 00:00:00 2001 From: eat-swap Date: Wed, 4 May 2022 18:35:52 +0800 Subject: [PATCH] add: 220504-CN [cpp] --- cpp/2205/220504-CN.cpp | 35 +++++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220504-CN.cpp diff --git a/cpp/2205/220504-CN.cpp b/cpp/2205/220504-CN.cpp new file mode 100644 index 0000000..1bebb69 --- /dev/null +++ b/cpp/2205/220504-CN.cpp @@ -0,0 +1,35 @@ +#include + +/** + * 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)); +} \ No newline at end of file diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index 1a74bc6..991851c 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220503.cpp) +ADD_EXECUTABLE(2204 220504-CN.cpp)