DEV Community

Discussion on: Data Structures & Algorithms using Rust: Find Numbers with Even Number of Digits

Collapse
 
sno2 profile image
Carter Snook

You can just use the bitwise AND (&) to check if a number is odd or not. Here is an example:

console.log(1 & 1); // logs `1`
console.log(2 & 1); // logs `0`
Enter fullscreen mode Exit fullscreen mode

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`
Enter fullscreen mode Exit fullscreen mode

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).

Collapse
 
ssivakumar profile image
Sivakumar

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.

Collapse
 
sno2 profile image
Carter Snook

Yes, but couldn't you do i_cnt & 1 instead of i_cnt % 2 == 0?

Thread Thread
 
ssivakumar profile image
Sivakumar

Yes, that can be refactored as you suggested.