查找给定数组中出现奇数次的元素的 Go 语言程序
示例
例如,arr = [1, 4, 5, 1, 4, 5, 1] => 数组中出现奇数次的元素是:1
解决此问题的步骤
步骤 1 − 定义接受数组的方法。
步骤 2 − 声明异或变量,即 xor := 0。
步骤 3 − 迭代输入数组,并对数组的每个元素执行 xor 操作。
步骤 4 − 最后,返回异或。
示例
package main import ( "fmt" ) func FindOddOccurringElement(arr []int) int{ xor := 0 for i := 0; i < len(arr); i++ { xor = xor ^ arr[i] } return xor } func main(){ arr := []int{1, 4, 5, 1, 4, 5, 1} fmt.Printf("Input array is: %d\n", arr) fmt.Printf("Odd occurring element in given array is: %d\n", FindOddOccurringElement(arr)) }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Input array is: [1 4 5 1 4 5 1] Odd occurring element in given array is: 1
广告