Skip to content

Commit

Permalink
Bitwise and of numbers range (#215)
Browse files Browse the repository at this point in the history
* add bitwise and of numbers range

* impl bitwise and of numbers range
  • Loading branch information
SKTT1Ryze authored Mar 20, 2024
1 parent d69c519 commit d43e1ad
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
40 changes: 40 additions & 0 deletions leetcode-cc/BitWiseANDOfNumRange.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include "TestHelper.h"
#include "problem.h"
#include "solution.h"

using namespace std;

IMPLEMENT_PROBLEM_CLASS(
PBitWiseANDOfNumRange, 201, DIFFI_MEDIUM, TOPIC_ALGORITHMS,
"Bit Wise AND Of Numbers Range",
"Given two integers left and right that represent the range [left, right], "
"return the bitwise AND of all numbers in this range, inclusive.",
{"Bit"});

class SBitWiseANDOfNumRange : public ISolution {
public:
size_t problemId() const override { return 201; }
string name() const override {
return ("Solution for " + string("Bit Wise AND Of Numbers Range"));
}
string location() const override { return __FILE_NAME__; }
int test() const override {
return testHelper<pair<int, int>, int>(
{{5, 7}, {0, 0}, {1, 2147483647}}, {4, 0, 0}, [this](auto input) {
return this->rangeBitwiseAnd(input.first, input.second);
});
};
int benchmark() const override { return 0; }

private:
int rangeBitwiseAnd(int left, int right) const {
int shift = 0;
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}

return left << shift;
}
};
7 changes: 7 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "../leetcode-cc/BestTimeToBuySellStockIV.hpp"
#include "../leetcode-cc/BinaryTreeInorderTraversal.hpp"
#include "../leetcode-cc/BinaryTreeLevelOrderTraversal.hpp"
#include "../leetcode-cc/BitWiseANDOfNumRange.hpp"
#include "../leetcode-cc/CloneGraph.hpp"
#include "../leetcode-cc/CmpVersionNum.hpp"
#include "../leetcode-cc/ConstructBTreeInorderPostorder.hpp"
Expand Down Expand Up @@ -819,5 +820,11 @@ const int registerAll(std::shared_ptr<Container> handle) {
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SDungeonGame>(); });

handle->registerProblem(
[]() -> ArcProblem { return std::make_shared<PBitWiseANDOfNumRange>(); });
handle->registerSolution([]() -> ArcSolution {
return std::make_shared<SBitWiseANDOfNumRange>();
});

return 0;
}

0 comments on commit d43e1ad

Please sign in to comment.