0

I'm looking over the solutions for a CodeWars problem (IQ Test) in which you're given a string of numbers and all the numbers but 1 are either even or odd. You need to return the index plus 1 of the position of the number that's not like the rest of the numbers.

I'm confused about the line that says & 1 in the solution posted below. The code doesn't work w/ && or w/ the & 1 taken away.

function iqTest(numbers){
  numbers = numbers.split(' ')

  var evens = []
  var odds = []

  for (var i = 0; i < numbers.length; i++) {
    if (numbers[i] & 1) { //PLEASE EXPLAIN THIS LINE!
      odds.push(i + 1)
    } else {
      evens.push(i + 1)
    }
  }

  return evens.length === 1 ? evens[0] : odds[0]
}

Also, would you consider using & 1 to be best practice or is it just "clever" code?

Gwater17
  • 1,328
  • 1
  • 12
  • 24

2 Answers2

2

The single & is a 'bitwise' operator. This specific operator (&) is the bitwise AND operator - which returns a one in each bit position for which the corresponding bits of both operands are ones.

The way it's being used here is to test if numbers[i] is an even or odd number. As i loops from 0 to numbers.length, for the first iteration the if statement evaluates 0 & 1 which evaluates to 0, or false. On the next iteration of the loop, the statement will be 1 & 1, which evaluates to 1, or true.

The result - when numbers[i] & 1 evaluates to 0, or false, then numbers[i] is pushed to the odd array. If numbers[i] & 1 evaluates to 1, or true, then numbers[i] is pushed to the even array.

An alternative to the & operator to test for even and odd is to use the modulo operator. numbers[i] % 2 results in the same output. That is, 1 % 2 results in 1, or true as will any odd number, because an odd number divided by 2 results in a remainder of 1. And any even number, like 2 % 2 results in 0 or false because an even number divided by 2 results in a remainder of 0.

As for your second question, is it 'clever or good?'. It's definitely clever. Whether it's good depends on who you ask and what your goal is. Many would say its less logical and harder to read than using num % 2.

Brett DeWoody
  • 50,328
  • 25
  • 121
  • 168
1

Binary number is 0 and 1 and each of them is called bit.

Single & is add operation and it works bitwise.

like

1 = 01
2 = 10 
3 = 11
4 = 100

You can see that every last bit of odd number is 1 and even number is 0.

In add operation

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

So only odd number will return 1 and even number will return 0 and in programming only 0 consider falsy.

If we wanna to check 5 is a odd or even

5  = 101

and perform and(&) operation with 1

  101 
& 001
-----
  001

and value of binary 001 is 1 in 10 base number

So it'll perform easy odd even process.

Anik Islam Abhi
  • 24,324
  • 8
  • 52
  • 74