From 8ef205ad1e6be018867969cb9cc1d2d314c4f51c Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Tue, 7 Nov 2023 08:40:33 -0700 Subject: [PATCH] day 35: 202-happy-number --- 202-happy-number/driver.cpp | 10 ++++++++++ 202-happy-number/soln.cpp | 33 +++++++++++++++++++++++++++++++++ 202-happy-number/soln.hpp | 8 ++++++++ 3 files changed, 51 insertions(+) create mode 100644 202-happy-number/driver.cpp create mode 100644 202-happy-number/soln.cpp create mode 100644 202-happy-number/soln.hpp diff --git a/202-happy-number/driver.cpp b/202-happy-number/driver.cpp new file mode 100644 index 0000000..61d7635 --- /dev/null +++ b/202-happy-number/driver.cpp @@ -0,0 +1,10 @@ +#include "soln.hpp" + +int main() +{ + int n = 42; + bool answer = false; + Solution soln; + cout << "Checked happy number correctly? " << soln.test(n, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/202-happy-number/soln.cpp b/202-happy-number/soln.cpp new file mode 100644 index 0000000..84e9f2b --- /dev/null +++ b/202-happy-number/soln.cpp @@ -0,0 +1,33 @@ +#include "soln.hpp" + +bool Solution::isHappy(int n) +{ + // naive + unordered_map occurrences{{n, true}}; + int tmp, tmp_sum; + while (n != 1) + { + tmp = n; + tmp_sum = 0; + while (tmp > 0) + { + tmp_sum += (tmp % 10) * (tmp % 10); + tmp /= 10; + } + // cycle + if (occurrences.find(tmp_sum) != occurrences.end()) + { + return false; + } + occurrences[tmp_sum] = true; + n = tmp_sum; + } + return n == 1; + + // floyd cycle finding is better +} + +bool Solution::test(int n, bool answer) +{ + return isHappy(n) == answer; +} \ No newline at end of file diff --git a/202-happy-number/soln.hpp b/202-happy-number/soln.hpp new file mode 100644 index 0000000..72060c2 --- /dev/null +++ b/202-happy-number/soln.hpp @@ -0,0 +1,8 @@ +#include +using namespace std; +class Solution +{ +public: + bool isHappy(int n); + bool test(int n, bool answer); +}; \ No newline at end of file