Skip to content

Instantly share code, notes, and snippets.

@pplanel
Created April 24, 2020 20:39
Show Gist options
  • Save pplanel/f68e86915b1cfcf473d95ba8ddeaf56a to your computer and use it in GitHub Desktop.
Save pplanel/f68e86915b1cfcf473d95ba8ddeaf56a to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cmath>
#include <set>
using namespace std;
auto getDigits = [](int n) -> int { return log10(n) + 1; };
auto getIndexedNumber = [](int n1, int n2) -> int { return (int) (n1 / pow(10, n2)) % 10; };
int reduceToHappy(int number){
int result = 0;
for(int i=0; i<getDigits(number); i++){
int digit = getIndexedNumber(number, i);
result += pow(digit, 2);
}
return result;
}
class Solution{
public:
Solution(){};
bool isHappy(int n){
set<int> store;
set<int>::iterator it_store;
int number = reduceToHappy(n);
while(number != 1){
number = reduceToHappy(number);
if(store.find(number) != store.end()){
return false;
}
store.insert(number);
}
return true;
}
};
int main(){
Solution* obj = new Solution();
if(obj->isHappy(19)){
cout << "Number is happy" << endl;
}else{
cout << "Number is not happy" << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment