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

Happy number #216

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
54 changes: 54 additions & 0 deletions leetcode-cc/HappyNumber.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include <unordered_set>

#include "TestHelper.h"
#include "problem.h"
#include "solution.h"

using namespace std;

IMPLEMENT_PROBLEM_CLASS(
PHappyNumber, 202, DIFFI_EASY, TOPIC_ALGORITHMS, "Harry Number",
"Write an algorithm to determine if a number n is happy.", {"Math"});

class SHappyNumber : public ISolution {
public:
size_t problemId() const override { return 202; }
string name() const override {
return ("Solution for " + string("Happy Number"));
}
string location() const override { return __FILE_NAME__; }
int test() const override {
return testHelper<int, bool>({19, 2}, {true, false}, [this](auto input) {
return this->isHappy(input);
});
};
int benchmark() const override { return 0; }

private:
bool isHappy(int n) const {
unordered_set<int> memo = {};
return check(n, memo);
}

static bool check(int n, unordered_set<int>& memo) {
if (n == 1) {
return true;
} else if (memo.contains(n)) {
return false;
} else {
memo.insert(n);
return check(calNum(n), memo);
}
}

static int calNum(int n) {
int res = 0;

while (n > 0) {
res += pow(n % 10, 2);
n /= 10;
}

return res;
}
};
6 changes: 6 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
#include "../leetcode-cc/FractionToDecimal.hpp"
#include "../leetcode-cc/GenerateParentheses.hpp"
#include "../leetcode-cc/GrayCode.hpp"
#include "../leetcode-cc/HappyNumber.hpp"
#include "../leetcode-cc/HouseRobber.hpp"
#include "../leetcode-cc/InsertDeleteGetrandomO1.hpp"
#include "../leetcode-cc/InsertionSortList.hpp"
Expand Down Expand Up @@ -826,5 +827,10 @@ const int registerAll(std::shared_ptr<Container> handle) {
return std::make_shared<SBitWiseANDOfNumRange>();
});

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

return 0;
}
Loading