leetcode 810. Chalkboard XOR Game

leetcode 810. Chalkboard XOR Game


原题地址:https://leetcode.com/problems/chalkboard-xor-game/

题目

We are given non-negative integers nums[i] which are written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. (Also, we’ll say the bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.)

Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.

Return True if and only if Alice wins the game, assuming both players play optimally.

Example:
Input: nums = [1, 1, 2]
Output: false
Explanation: 
Alice has two choices: erase 1 or erase 2. 
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. 
If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.

Note:

  • 1 <= N <= 1000.
  • 0 <= nums[i] <= 2^16.

    这道题有些歧义,几位大佬在讨论为啥[1,2,3]的结果是true,他们认为最开始是一定由Alice开始的,可是要想解这道题,如果最开始结果就是0的话,那么就直接默认Alice赢,所以[1,2,3]的结果为true。
    判断初始条件,只要初始结果不为零,那么一定存在两个不相同的nums[i],这时候只要去选与结果不同的即可。多以只要给定数组为偶数个,那么Alice就可以赢,奇数的话Alice擦掉一个数后就相当于Bob站在了偶数个时候Alice的角度,所以Bob赢。如果只考虑数组长度,就会造成[1,2,3]返回false的情况。

python代码

class Solution:
    def xorGame(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        result = 0
        for i in nums: 
            result = result ^ i
        if result == 0 or len(nums) % 2 == 0:
            return True
        else:
            return False

版权声明:转载注明 http://blog.csdn.net/birdreamer/article/details/79781069

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值