Day 2 of 30-Day LeetCode Challenge

Aanchal Patial
1 min readApr 14, 2020

Write an algorithm to determine if a number n is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Return True if n is a happy number, and False if not.

class Solution {
public:
unsigned long long sumOfSquares(unsigned long long n){
unsigned long long result = 0;
while(n>0){
result += pow(n%10, 2);
n /= 10;
}
return result;
}
bool isHappy(int n) {

//Method 1) : Using Hash
// unordered_set<unsigned long long> s;
// unsigned long long num = n;
// while(s.find(num)==s.end()){
// s.insert(num);
// num = sumOfSquares(num);
// if(num==1) return true;
// }
// return false;

//Method 2) : Using Recursion
int slow = n;
int fast = n;
do{
slow = sumOfSquares(slow);
fast = sumOfSquares(sumOfSquares(fast));
}while(slow!=fast);
if(slow==1) return true;
else return false;
}
};

--

--

Aanchal Patial

We never really grow up, we only learn how to act in public