day 35: 202-happy-number

This commit is contained in:
Kaushik Narayan R 2023-11-07 08:40:33 -07:00
parent 2e3c839ec5
commit 8ef205ad1e
3 changed files with 51 additions and 0 deletions

View File

@ -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;
}

33
202-happy-number/soln.cpp Normal file
View File

@ -0,0 +1,33 @@
#include "soln.hpp"
bool Solution::isHappy(int n)
{
// naive
unordered_map<int, bool> 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;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isHappy(int n);
bool test(int n, bool answer);
};