mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 06:24:07 +00:00
day 35: 202-happy-number
This commit is contained in:
parent
2e3c839ec5
commit
8ef205ad1e
10
202-happy-number/driver.cpp
Normal file
10
202-happy-number/driver.cpp
Normal 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
33
202-happy-number/soln.cpp
Normal 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;
|
||||
}
|
||||
8
202-happy-number/soln.hpp
Normal file
8
202-happy-number/soln.hpp
Normal 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);
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user