Check Happy Number

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

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.
  • 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.

Return true if n is a happy number, and false if not.

Example 1:

Input: num =13
Output: Happy Number   //i.e 1*1+3*3=10, 1*1+0*0=1
Explanation: A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. 

Approach:

Java


public class HappyNumber {
    public static void main(String[] args) {
        int num = 14;
        if (isHappy(num))
            System.out.println("Happy Number");
        else
            System.out.println("Not happy number");
    }

    public static boolean isHappy(int n) {
        int prev = n;
        // sum of given number
        int next = sumOfSquareDigits(n);
        // iterate untill both equal
        while (prev != next) {
            // previuos sum
            prev = sumOfSquareDigits(prev);
            // next sum
            next = sumOfSquareDigits(sumOfSquareDigits(next));

            if (next == 1)
                return true;
        }

        return prev == 1;
    }

    // method to find the each digit square sum
    static int sumOfSquareDigits(int num) {
        int sum = 0;
        while (num > 0) {
            int digit = num % 10;
            sum += digit * digit;
            num = num / 10;
        }
        return sum;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

//function to find the
//each digit square sum
int sumOfSquareDigits(int num)
{
    int sum=0;
    while(num>0)
      {
          int digit=num%10;
          sum+=digit*digit;
          num=num/10;
      }
    return sum;
}

//function to check the 
//given number is happy or
//not
bool isHappy(int num)
{
   set<intst;
   while(num>1&&(st.find(num)==st.end()))
     {
        st.insert(num);
        num=sumOfSquareDigits(num);
     }

//if number becomes 1 then
//the number is happy
    if(num==1)
       return true;

 //else the numbe is not
 //happy
    else
      return false;
}
int main()
{
    int num=13;
    if(isHappy(num))
      cout<<"Happy Number\n";
    else
     cout<<"Not happy number\n";
}


No comments:

Post a Comment