Header Ad

Leetcode Happy Number problem solution

In this Leetcode Happy Number problem solution Write an algorithm to determine if a number n is happy.

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

Leetcode Happy Number problem solution


Problem solution in Python.

class Solution(object):
    def isHappy(self, n, prev=[]):
        nums = sum([int(x)**2 for x in list(str(n))])
        if nums in prev:
            return False
        return self.isHappy(nums, prev+[nums]) if nums != 1 else True



Problem solution in Java.

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<>();
        while(n != 1){
            if(set.contains(n)){
                return false;
            }
            set.add(n);
            n = sum(n);
        }
        return true;
    }
    
    public int sum(int n){
        int sum = 0;
        while(n > 0){
            sum += (n%10) * (n%10);
            n = n/10;
        }
        return sum;
    }
}


Problem solution in C++.

class Solution {
public:
    map<int, int> terminate;
    bool isHappy(int n) {
        int temp = 0;
        if(n==1){
            return 1;
        }
        while(n!=0){
            temp += pow(n%10, 2);
            n = n/10;
        }
        if(terminate[temp] == 0){
            terminate[temp] = 1;
        } else{
            return 0;
        }
        return isHappy(temp);
    }
};


Problem solution in C.

int key[1000],i = 0;
int count = 0,temp;
while(i<1000)       //Initialize
	key[i++]=1;

for(;n;n/=10)            
	{
		temp=n%10;
		count+=temp*temp;
	}
if(count==1) return true;

n=count;
while(key[n])
{
	
	int x=n;
	count=0;
	for(;n;n/=10)
		{
			temp=n%10;
			count+=temp*temp;
		}
	if(count==1) return true;
	else
	{
		key[x]=0;
		n=count;
	}
}
return false;


Post a Comment

0 Comments