Skip to content

1908. Game of Nim

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
class Solution {
 public:
  bool nimGame(vector<int>& piles) {
    return accumulate(piles.begin(), piles.end(), 0, bit_xor<>()) > 0;
  }
};
1
2
3
4
5
class Solution {
  public boolean nimGame(int[] piles) {
    return Arrays.stream(piles).reduce((a, b) -> a ^ b).getAsInt() > 0;
  }
}
1
2
3
class Solution:
  def nimGame(self, piles: list[int]) -> bool:
    return functools.reduce(operator.xor, piles) > 0