xdxdxd123

Untitled

Jun 17th, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. In an array of integers, all elements appear even times except one appears odd times. Find that element. Please give an O(n)-time algorithm. For example: input array: [1,2,3,3,2,1,1,1,2], should output 2
  2.  
  3. Expert Answer
  4. Darshan
  5. Darshan answered this Was this answer helpful?
  6. 0
  7. 0
  8. 104 answers
  9. The best solution without using any memory is use Bitwise XOR Operator and XOR all the elements , so if you XOR all the elements the output will be the element that apper odd times.
  10.  
  11. Because XOR of element with itself is 0. ( e.g 1 XOR 1 = 0 ), so the only odd element will be left at last.
  12.  
  13. Algorithm:
  14.  
  15. int getOddNumber(int ar[], int size)
  16.  
  17. {
  18.  
  19. int i;
  20.  
  21. int out = 0;
  22.  
  23. for (i=0; i < size; i++){
  24.  
  25. out = out ^ ar[i]; // XOR operation
  26.  
  27. }
  28.  
  29. return out;
  30.  
  31. }
Add Comment
Please, Sign In to add comment