题解 | #牛的编号异或问题#
牛的编号异或问题
https://www.nowcoder.com/practice/b8139d2af0f64e6489f69cb173f170c1
- 题目考察的知识点: 位运算:异或
- 题目解答方法的文字分析
- 将整数按照余数0、1、2、3分组,每组内的数异或为0。
- 因此只需关注每组的一个代表元素:余0:代表元素为left,余1:代表元素为1,余2:代表元素为left+1,余3:代表元素为0
- 右端点right根据其余数,决定取哪个代表元素进行异或运算
- 最终根据left的余数取代表元素,与right对应的代表元素异或,就得到了整个区间的异或结果
- 本题解析所用的编程语言:Python3
- 完整且正确的编程代码
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param left int整型 # @param right int整型 # @return int整型 # class Solution: def rangeBitwiseXor(self, left: int, right: int) -> int: # write code here result = 0 if left % 4 == 0: result = left elif left % 4 == 1: result = 1 elif left % 4 == 2: result = left + 1 else: result = 0 group = [right, 1, right + 1, 0] return result ^ group[right % 4]
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路