• + 0 comments

    My Java solution :

    /* Finds the winner of the game. Returns true if "First" wins */
        private static boolean isFirstPlayerWinner(int[] stones) {
            /* In a single pile, if more than one stones exist then first player will
             * always win by leaving the last stone for second player to pick up
             */
            if (stones.length == 1) {
                return stones[0] > 1;
            }
            
            int totalStones = stones[0];
            int xorValue = stones[0];
            
            for (int s = 1; s < stones.length; s++) {
                totalStones += stones[s];
                xorValue ^= stones[s];
            }
            
            /* If sum of all stones equals the total piles, all piles have a single (1)
             * stone. For even number of piles, first player will always win.
             */
            if (totalStones == stones.length) {
                return totalStones % 2 == 0;
            }
            
            /* For all other cases, the xor value determines winner. If xor value = 0,
             * then second player will always win as all piles (stones) can be paired. 
             */
            return xorValue > 0;
        }