Skip to content

Commit

Permalink
Happy number (#216)
Browse files Browse the repository at this point in the history
* add happy number

* impl happy number
  • Loading branch information
SKTT1Ryze authored Mar 20, 2024
1 parent d43e1ad commit 1c3df52
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
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;
}

0 comments on commit 1c3df52

Please sign in to comment.