From 39a99b46f5e9b2c56951c22189a8ac3ea0730b01 Mon Sep 17 00:00:00 2001 From: Laukik Chahande <103280327+luciferx48@users.noreply.github.com> Date: Sun, 23 Oct 2022 22:56:22 +0530 Subject: [PATCH] check whether integer is even or odd using bit manupulation (#7099) * even_or_not file added * Updated DIRECTORY.md * modified DIRECTORY.md * Update bit_manipulation/even_or_not.py * updating DIRECTORY.md * Rename even_or_not.py to is_even.py * updating DIRECTORY.md Co-authored-by: luciferx48 Co-authored-by: Christian Clauss Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- DIRECTORY.md | 1 + bit_manipulation/is_even.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 bit_manipulation/is_even.py diff --git a/DIRECTORY.md b/DIRECTORY.md index 3fd1a3c38..10e78a92c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -45,6 +45,7 @@ * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) + * [Is Even](bit_manipulation/is_even.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) diff --git a/bit_manipulation/is_even.py b/bit_manipulation/is_even.py new file mode 100644 index 000000000..b7b0841a1 --- /dev/null +++ b/bit_manipulation/is_even.py @@ -0,0 +1,37 @@ +def is_even(number: int) -> bool: + """ + return true if the input integer is even + Explanation: Lets take a look at the following deicmal to binary conversions + 2 => 10 + 14 => 1110 + 100 => 1100100 + 3 => 11 + 13 => 1101 + 101 => 1100101 + from the above examples we can observe that + for all the odd integers there is always 1 set bit at the end + also, 1 in binary can be represented as 001, 00001, or 0000001 + so for any odd integer n => n&1 is always equlas 1 else the integer is even + + >>> is_even(1) + False + >>> is_even(4) + True + >>> is_even(9) + False + >>> is_even(15) + False + >>> is_even(40) + True + >>> is_even(100) + True + >>> is_even(101) + False + """ + return number & 1 == 0 + + +if __name__ == "__main__": + import doctest + + doctest.testmod()