ในการหาจำนวนที่เกิดขึ้นเป็นจำนวนคี่ รหัส Java มีดังต่อไปนี้ -
ตัวอย่าง
public class Demo {
static int odd_occurs(int my_arr[], int arr_size){
int i;
for (i = 0; i < arr_size; i++){
int count = 0;
for (int j = 0; j < arr_size; j++){
if (my_arr[i] == my_arr[j])
count++;
}
if (count % 2 != 0)
return my_arr[i];
}
return -1;
}
public static void main(String[] args){
int my_arr[] = new int[]{ 34, 56, 99, 34, 55, 99, 90, 11, 12, 11, 11, 34 };
int arr_size = my_arr.length;
System.out.println("The number that occurs odd number of times in the array is ");
System.out.println(odd_occurs(my_arr, arr_size));
}
} ผลลัพธ์
The number that occurs odd number of times in the array is 34
คลาสชื่อ Demo มีฟังก์ชันสแตติกชื่อ 'odd_occurs' ฟังก์ชันนี้จะวนซ้ำผ่านอาร์เรย์จำนวนเต็ม และตรวจสอบเพื่อดูจำนวนครั้งที่ตัวเลขเหล่านี้เกิดขึ้น จำนวนคี่ที่เกิดขึ้นบ่อยครั้งจะถูกส่งกลับเป็นผลลัพธ์ ในฟังก์ชันหลัก อาร์เรย์จำนวนเต็มถูกกำหนด และความยาวของอาร์เรย์ถูกกำหนดให้กับตัวแปร ฟังก์ชันนี้ถูกเรียกโดยการส่งผ่านอาร์เรย์ และความยาวเป็นพารามิเตอร์ ข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล