HPYNOS - Happy Numbers I editorial spoj - UCS - Unleash-Coding-Skills

Monday, 7 May 2018

HPYNOS - Happy Numbers I editorial spoj - UCS

                 HPYNOS - Happy Numbers I:

The link for the problem HPYNOS - Happy Numbers I is :

http://www.spoj.com/problems/HPYNOS/

 The solution for the problem is very the process is terminated when we encountered a repeated number in a cycle. To find the repeated number we use an array to keep track of the already used numbers.

Note:
Take care of 32 nd test case . Its input is 7 and output is 5 and you must also take care about other single digit inputs.For only 1 and 7 you will get different outputs remaining all single digit numbers will get '-1' as output.

The Java solution for the above problem HPYNOS - Happy Numbers I is:


import java.util.*;
import java.lang.*;

class Main
{
         public static  int convert(int n)
    {
        int temp,r=0;
        while(n>0)
        {
            temp = n%10;
            n=n/10;
            r+=temp*temp;
            
        }
        return r;
    }
    public static void main (String[] args) throws java.lang.Exception
    {
    
         List<Integer> ls = new ArrayList<>();
     Scanner s = new Scanner(System.in);
        int n = s.nextInt();
for(int i=0;i<=3000000;i++)
    ls.add(0);
        int count=0;
        int fl=0;
        while(true)
        {
              int u;
         int temp=0;
            temp=convert(n);
           
            u=ls.get(temp);
            n=temp;
               count++;
            if(n==1){
                fl=0;
                break;
            }
            if(ls.get(temp)==0)
            {
            ls.add(temp,1);
              
             
            }
            else
            {
                fl=1;
                break;
            }
        }
        if(fl==1)
        {
           System.out.println("-1");
        }
        else{
            System.out.println(count);
        }
           
    }
}



Happy Coding.........

No comments:

Post a comment