Finding the Single Odd Occurrence

Using XOR, iterate through an array where elements appear twice except one. XOR cancels pairs, leaving the odd-occurrence element.

Syntax:

let result = 0;
for (let num of nums) {
result ^= num;
}

Example: In this example, XOR array elements, cancel pairs, and find an element occurring once.

Javascript




let n = [5, 4, 6, 8, 3];
let result = 0;
for (let num of n) {
    result ^= num;
}
console.log("element that occurs only once:", result);


Output

element that occurs only once: 12

Bit manipulation in JavaScript

Bit manipulation in JavaScript refers to the manipulation and operation of individual bits within binary representations of numbers and JavaScript uses 32-bit signed integers for numeric values. It involves using bitwise operators (&, |, ^, ~, <<, >>) to manipulate individual bits of binary numbers. These operations can be used for bitwise logic operations such as AND, OR, XOR, and shifting bits.

Below is a list of bitwise operators:

  • Bitwise AND(&): Returns true if both operands are true.
  • Bitwise OR(|): Returns true even if one operand is true.
  • Bitwise XOR(^): Returns true if both operands are different.
  • Bitwise NOT(~): Flips the value of the operand.
  • Bitwise Left Shift(<<): Shifts the bit toward the left.
  • Bitwise Right Shift(>>): Shifts the bit towards the right.
  • Zero Fill Right Shift(>>>): Shifts the bit towards the right but adds 0 from the left.

Below we will describe the common bit manipulation problems in detail:

Table of Content

  • Checking Odd or Even
  • Swap Two Numbers
  • Finding the Single Odd Occurrence
  • Power of Two Checks
  • Count Total Bits Set

Similar Reads

Checking Odd or Even

...

Swap Two Numbers

In this approach, we are using bitwise AND (&) to check the least significant bit of n. If it’s set (odd), “odd” is printed; otherwise, “even” is printed....

Finding the Single Odd Occurrence

...

Power of Two Checks

In this approach we Swap two variables using bitwise XOR by applying XOR twice to each variable, cancelling out the effect and achieving the swap without extra storage....

Count Total Bits Set

...

Contact Us