The reason this works is because the AND operator checks if the bits (in 2 bit) on the two things are matching. In our case, these are 10-bit numbers. Our 10-bit numbers will be converted into 2 bits. If all present bits are equal, then it returns 1, else 0. Here is a figurative expression of the code above:
// These numbers are in 2-bits
1 AND 1 // returns `1`
10 AND 1 // returns `0`
In the first case, both numbers have a 1 in the 1s place, so it returns 1 (true). In the second case, the first number has a 0 in the 1s place, but the second number has a 1, therefore it returns 0 (false).
As per my understanding, the problem statement is to find an element in Array which is "Even" interms of number of digits. For ex: 342 is an Even number but in terms of number of digits it is not "Even".
You can just use the bitwise AND (
&
) to check if a number is odd or not. Here is an example:The reason this works is because the AND operator checks if the bits (in 2 bit) on the two things are matching. In our case, these are 10-bit numbers. Our 10-bit numbers will be converted into 2 bits. If all present bits are equal, then it returns 1, else 0. Here is a figurative expression of the code above:
In the first case, both numbers have a 1 in the 1s place, so it returns 1 (true). In the second case, the first number has a 0 in the 1s place, but the second number has a 1, therefore it returns 0 (false).
Thanks Coding Carter for your feedback.
As per my understanding, the problem statement is to find an element in Array which is "Even" interms of number of digits. For ex: 342 is an Even number but in terms of number of digits it is not "Even".
Hope this explains.
Please feel free to share your feedback.
Yes, but couldn't you do
i_cnt & 1
instead ofi_cnt % 2 == 0
?Yes, that can be refactored as you suggested.