ภาพรวม
สร้างอาร์เรย์ nums ขนาด n โดย nums[i] = start + 2*i แล้วหาค่า Bitwise XOR ของทุกสมาชิก
ตัวอย่าง
n = 6, start = 2
อาร์เรย์: [2, 4, 6, 8, 10, 12]
XOR: 2 ^ 4 ^ 6 ^ 8 ^ 10 ^ 12 = 14
ขั้นตอนการแก้ปัญหา
- ตั้งค่า
count = start - วนลูป
while n-1 > 0:count ^= (2 + start)n -= 1start += 2
- คืนค่า
count
ตัวอย่างโค้ด (Python)
def solve(n, start):
count = start
while n - 1 > 0:
count ^= 2 + start
n -= 1
start += 2
return count
n = 6
start = 2
print(solve(n, start))
อินพุต
6, 2
เอาต์พุต
14
วิธีเขียนอีกแบบ (Pythonic)
from functools import reduce
from operator import xor
def solve_pythonic(n, start):
return reduce(xor, (start + 2*i for i in range(n)))