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.

GoData Integrity

Code

gosnippet
19 lines
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

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.