Single Number Found By Xor
Cancel out duplicate values with a single xor accumulator: identical pairs annihilate, leaving the one number that appears exactly once in the slice.
Code
package main
import "fmt"
// single number found by xor: identical pairs cancel, the loner survives
func singleNumber(nums []int) int {
result := 0
for _, n := range nums {
result ^= n
}
return result
}
func main() {
series := []int{4, 1, 2, 1, 2}
fmt.Println("single:", singleNumber(series))
// 异或满足交换律与结合律:结果与元素顺序无关
fmt.Println("same:", singleNumber([]int{1, 4, 2, 1, 2}))
}Single Number Found By Xor: the mechanics
Under the hood: the functions singleNumber and main.
The loop for _, n := range nums is the only repeated construct.
Points of care
- Only built-in APIs, which leaves no supply chain to audit.
Using it
Top of the API surface: func singleNumber(nums []int) int
The run emits 2 labeled sections — single:, same: — one per step.
There are 1 call inside main — singleNumber — executed top to bottom.
Key statements
func singleNumber(nums []int) int {
result := 0
for _, n := range nums {
result ^= n
}
return result
}
func main() {
series := []int{4, 1, 2, 1, 2}
fmt.Println("single:", singleNumber(series))
// 异或满足交换律与结合律:结果与元素顺序无关
fmt.Println("same:", singleNumber([]int{1, 4, 2, 1, 2}))
}
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.
FAQ
- What does Single Number Found By Xor print when run?
- No setup needed: run the file and look for labeled lines like `single:`, `same:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.