查詢給定陣列中出現奇數次的元素的 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))
}輸出
Input array is: [1 4 5 1 4 5 1] Odd occurring element in given array is: 1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP