Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bitwise and of numbers range #215

Merged
merged 2 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading