292. Nim Game Easy
1/**
2 * [292] Nim Game
3 *
4 * You are playing the following Nim Game with your friend:
5 *
6 * Initially, there is a heap of stones on the table.
7 * You and your friend will alternate taking turns, and you go first.
8 * On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
9 * The one who removes the last stone is the winner.
10 *
11 * Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.
12 *
13 * Example 1:
14 *
15 * Input: n = 4
16 * Output: false
17 * Explanation: These are the possible outcomes:
18 * 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
19 * 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
20 * 3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
21 * In all outcomes, your friend wins.
22 *
23 * Example 2:
24 *
25 * Input: n = 1
26 * Output: true
27 *
28 * Example 3:
29 *
30 * Input: n = 2
31 * Output: true
32 *
33 *
34 * Constraints:
35 *
36 * 1 <= n <= 2^31 - 1
37 *
38 */
39pub struct Solution {}
40
41// problem: https://leetcode.com/problems/nim-game/
42// discuss: https://leetcode.com/problems/nim-game/discuss/?currentPage=1&orderBy=most_votes&query=
43
44// submission codes start here
45
46impl Solution {
47 pub fn can_win_nim(n: i32) -> bool {
48 n % 4 != 0
49 }
50}
51
52// submission codes end
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57
58 #[test]
59 fn test_292() {
60 assert!(!Solution::can_win_nim(4));
61 assert!(Solution::can_win_nim(1));
62 assert!(Solution::can_win_nim(2));
63 assert!(Solution::can_win_nim(3));
64 }
65}
66
Back
© 2025 bowen.ge All Rights Reserved.