From 8765118a48d1ea1a5e6c95e0d583aa410b486f03 Mon Sep 17 00:00:00 2001 From: Fazeel Usmani Date: Sun, 10 Oct 2021 23:54:28 +0530 Subject: [PATCH] Create 10_bitwiseAnd.cpp --- .../10_bitwiseAnd.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 10 October LeetCode Challenge 2021/10_bitwiseAnd.cpp diff --git a/10 October LeetCode Challenge 2021/10_bitwiseAnd.cpp b/10 October LeetCode Challenge 2021/10_bitwiseAnd.cpp new file mode 100644 index 0000000..c627314 --- /dev/null +++ b/10 October LeetCode Challenge 2021/10_bitwiseAnd.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int rangeBitwiseAnd(int m, int n) { + // edge case - zero AND anything will always stay zero + if ((m == 0) || (n == 0)) return 0; + + // if there is a different amount of digits in binary - always will be zero + if ((int)log2(m) != (int)log2(n)) return 0; + + // None of the above - not too many numbers left to calculate one by one... + int res = m; + for (long i = m; i <= n; i++) + res &= i; + + return res; + } +};