LeetCode75-136-Single-Number

🧠 Summary of Thoughts

Use the bitwise XOR (^) operation to cancel out duplicate numbers.

XOR has two important properties:

  • a ^ a = 0 → same numbers cancel out
  • a ^ 0 = a → zero does not affect the result

Every number that appears twice cancels itself out. The only number left is the one that appears once. We can also reorder the ^’s left and right number to cancel the duplicate out :)

✅ Code(Java)

1
2
3
4
5
6
7
8
9
class Solution {
public int singleNumber(int[] nums) {
int ans = 0;
for (int num : nums) {
ans ^= num;
}
return ans;
}
}

LeetCode75-136-Single-Number
https://powersixxx.github.io/leetcode-blog/2026/04/11/LeetCode75-136-Single-Number/
作者
Baowen Liu
发布于
2026年4月11日
许可协议