Happy Number

Monisha Mathew
2 min readJun 4, 2019

--

Question: Write an algorithm to determine if a number 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.

Example:

Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

You may view the full question here.

Approach 1: Using HashMaps to store the evaluated values to detect repetitions.

//Approach 1:
//Runtime: 2ms
//Memory usage: 33MB
class Solution {

public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet();
set.add(n);
int sum = n;
while(sum!=1){
sum = getDigitSqrSum(sum);
if(set.contains(sum)){
return false;
} else {
set.add(sum);
}
}
return true;
}

private int getDigitSqrSum(int n){
int sum = 0;
while(n!=0){
int d = n%10;
sum+=(d*d);
n=n/10;
}
return sum;
}
}

Approach 2: Using cycle detection algorithms such as the Floyd’s Tortoise and the Hare algorithm. You may look up more such algorithms here.

//Approach 2:
//Runtime: 1ms
//Memory usage: 32.6MB
class Solution {
//Using Floyd Cycle detection algorithm
public boolean isHappy(int n) {
int slow, fast;
slow = fast = n;
do {
slow = digitSquareSum(slow);
fast = digitSquareSum(fast);
fast = digitSquareSum(fast);
} while(slow != fast);
if (slow == 1) return true;
else return false;
}

private int digitSquareSum(int n) {
int sum = 0, tmp;
while (n>0) {
tmp = n % 10;
sum += tmp * tmp;
n /= 10;
}
return sum;
}
}

Find more posts here.

Cheers & Chao!

--

--