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.
- 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");elseSystem.out.println("Not happy number");}public static boolean isHappy(int n) {int prev = n;// sum of given numberint next = sumOfSquareDigits(n);// iterate untill both equalwhile (prev != next) {// previuos sumprev = sumOfSquareDigits(prev);// next sumnext = sumOfSquareDigits(sumOfSquareDigits(next));if (next == 1)return true;}return prev == 1;}// method to find the each digit square sumstatic 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 sumint 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//notbool isHappy(int num){set<int> st;while(num>1&&(st.find(num)==st.end())){st.insert(num);num=sumOfSquareDigits(num);}//if number becomes 1 then//the number is happyif(num==1)return true;//else the numbe is not//happyelsereturn false;}int main(){int num=13;if(isHappy(num))cout<<"Happy Number\n";elsecout<<"Not happy number\n";}
No comments:
Post a Comment