Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To give more elaboration on the bitwise operator method for those of us who didn't do much boolean algebra during our studies, here is an explanation. Probably not of much use to the OP, but I felt like making it clear why NUMBER &amp; 1 works. </p> <p>Please note like as someone answered above, the way negative numbers are represented can stop this method working. In fact it can even break the modulo operator method too since each language can differ in how it deals with negative operands. </p> <p>However if you know that NUMBER will always be positive, this works well.</p> <p>As Tooony above made the point that only the last digit in binary (and denary) is important.</p> <p>A boolean logic AND gate dictates that both inputs have to be a 1 (or high voltage) for 1 to be returned.</p> <p>1 &amp; 0 = 0.</p> <p>0 &amp; 1 = 0. </p> <p>0 &amp; 0 = 0.</p> <p>1 &amp; 1 = 1.</p> <p>If you represent any number as binary (I have used an 8 bit representation here), odd numbers have 1 at the end, even numbers have 0.</p> <p>For example:</p> <p>1 = 00000001</p> <p>2 = 00000010</p> <p>3 = 00000011</p> <p>4 = 00000100</p> <p>If you take any number and use bitwise AND (&amp; in java) it by 1 it will either return 00000001, = 1 meaning the number is odd. Or 00000000 = 0, meaning the number is even.</p> <p>E.g</p> <p>Is odd?</p> <p>1 &amp; 1 = </p> <p>00000001 &amp;</p> <p>00000001 =</p> <p>00000001 &lt;— Odd</p> <p>2 &amp; 1 =</p> <p>00000010 &amp;</p> <p>00000001 =</p> <p>00000000 &lt;— Even</p> <p>54 &amp; 1 =</p> <p>00000001 &amp;</p> <p>00110110 =</p> <p>00000000 &lt;— Even</p> <p>This is why this works:</p> <pre><code>if(number &amp; 1){ //Number is odd } else { //Number is even } </code></pre> <p>Sorry if this is redundant.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload