well, to make it work with negative numbers you can just check if the number is negative and if it is, multiply with -1 (or just use abs).
The only issue with your algorithm is efficiency; runs in o(n). Some other ideas:
- Checking the least significant bit (which is probably the last)
- Integer division with 2 (could be done by dividing and trunc), the
multiply the result with 2 and check if it's the same number
Check if the last digit is 0,2,4,6,8 (really good if the number is given as
a string/array) In each step of your algorithm increase the
subtracted number till you hit negative then reverse the process. For
example, let's say we want to check 64:
- 64 - 2 = 62, it's >0 but not 0 or 1
- 63 - 4 = 58, >0, not 0/1
- 50 - 8 = 42, >0, not 0/1
- 42 -16 = 26, >0, not 0/1
- 26 -32 = -6, <0 => reverse
- 26 -16 = 10, >0, not 0/1
- 10 - 8 = 2, >0, not 0/1
- 2 - 4 = -2, <0 => reverse
- 2 - 2 = 0, =0 => even
So 10 steps instead of 63.
Note that after the first reverse, we decrease the subtracted number on each step because we know that it's less than 2x the number we subtract. Of course, you can create a ton of variations, some of them which are probably more efficient.
if (n and 1) = 1 then? - Michaelandis a boolean operator not a bitwise operator. At least not in the original Pascal. - lhf