From 7391bb88d878cfb629bd1c61b487f5bfb4a43b5c Mon Sep 17 00:00:00 2001 From: = Date: Sat, 31 Oct 2020 08:02:03 +0530 Subject: [PATCH] BitManipulation --- BitManipulation/countSetBits.py | 17 +++++++++++++++++ BitManipulation/nextpowOf2.py | 12 ++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 BitManipulation/countSetBits.py create mode 100644 BitManipulation/nextpowOf2.py diff --git a/BitManipulation/countSetBits.py b/BitManipulation/countSetBits.py new file mode 100644 index 00000000..7e2966a5 --- /dev/null +++ b/BitManipulation/countSetBits.py @@ -0,0 +1,17 @@ +# Function to get no of set bits in binary +# representation of positive integer n (iterative approach) +def countSetBits(n): + count = 0 + while (n): + count += n & 1 + n >>= 1 + return count + + +# Program to test function countSetBits +# std input would also work +i = 9 +print(countSetBits(i)) + +# contributed by +# Sampark Sharma diff --git a/BitManipulation/nextpowOf2.py b/BitManipulation/nextpowOf2.py new file mode 100644 index 00000000..83c5ab87 --- /dev/null +++ b/BitManipulation/nextpowOf2.py @@ -0,0 +1,12 @@ +def nextPowOf2(n): + p = 1 + if (n and not(n & (n - 1))): + return n + while (p < n) : + p <<= 1 + return p; + +t = int(input()) +for i in range(t): + n= int(input()) + print("Next Power of 2 " + str(nextPowOf2(n)))