online advertising

Tuesday, October 13, 2015

LeetCode OJ - Nim Game

Problem:

Please find the problem here.

Solution:

The key idea is that, if the game does not start n stones such that n % 4 == 0, the starter can always make that so. As long as the starter keep making sure the heap of stones is a multiple of 4, eventually he will win.

Code:

#include "stdafx.h"

// https://leetcode.com/problems/nim-game/

#include "LEET_NIM_GAME.h"
#include <map>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

namespace _LEET_NIM_GAME
{
    class Solution
    {
    public:
        bool canWinNim(int n)
        {
            return ((n % 4) != 0);
        }
    };
};

using namespace _LEET_NIM_GAME;

int LEET_NIM_GAME()
{
    Solution solution;
    for (int i = 1; i <= 10; i++)
    {
        cout << solution.canWinNim(i) << endl;
    }

    return 0;
}

No comments :

Post a Comment