fork download
  1. #include <iostream>
  2. using namespace std;
  3. /*
  4. Input: n = 19
  5. Output: true
  6. Explanation:12 + 92 = 82
  7. 82 + 22 = 68
  8. 62 + 82 = 100
  9. 12 + 02 + 02 = 1
  10. */
  11. int func1(int n) {
  12. int sum = 0;
  13.  
  14. while( n > 0) {
  15. int digit = n % 10;
  16. sum = sum + (digit * digit);
  17. n = n / 10;
  18. }
  19.  
  20. return sum;
  21. }
  22.  
  23. bool isHappy(int n) {
  24. int slow = n;
  25.  
  26. int fast = func1(n);
  27.  
  28. while(fast != 1 && slow != fast) {
  29. slow = func1(slow);
  30. fast = func1(func1(fast));
  31. }
  32. if(fast == 1)
  33. return true;
  34. else
  35. return false;
  36. }
  37.  
  38. int main() {
  39. int n;
  40. cin>>n;
  41. cout<< isHappy(n)<<endl;
  42. return 0;
  43. }
Success #stdin #stdout 0s 5320KB
stdin
2
stdout
0