Find the number which occurs odd number of time. All numbers occur even number of times except one.

import java.util.HashMap;
import java.util.Map;

public class Test {

 public static void main(String[] args) {

  //integer array declared with values
  int array[] = { 20, 40, 50, 40, 50, 20, 30, 30, 50, 20, 40, 40, 20};

  //declared map
  Map<Integer, Integer> map = new HashMap<>();

  //iterating int array to get the frequency of numbers
  for (int i = 0; i < array.length; i++) {
   if (map.containsKey(array[i])) {
    Integer value = (Integer) map.get(array[i]);

    map.put(array[i], ++value);
   } else {
    int key = array[i];

    map.put(key, 1);
   }
  }
  //iterating map to get the number which is present odd times
  map.forEach((key, value) -> {
      if(value % 2 != 0) {
       System.out.print("Number which occurs odd number of times is : 
       "+key);
      }
  });
 }
}

Share:

No comments:

Post a Comment

Quote of the day

Popular Posts

Featured Post

Collection Framework Overview

Collection:- A collection (sometimes called a container) is simply an object that groups multiple elements into single unit. Collect...

Youtube Page

Facebook Page

Recent Posts

About

I am Shivaji Chandra and I'm a Computer Science Engineer. I love to write poems, jokes and quotes. click here →