Magic number in java


Magic number in java

Magic number in java

/**
 * Magic number are 10, 19
 * If sum of all digits of the enter numberber become 1 then it is a Magic Number
 * For example 19 We first add 1+9 = 10 and then 1 + 0 = 1.
 * So here resultan value is 1 and it is a magic number.
 *
 * Inspire Skills
 * Khurshid Md Anwar
 */
import java.util.*;
public class MagicNumbers
{
    static Scanner sc=new Scanner(System.in);
    static int number=0;
    // Input Method, which a take a value
    private void input()
    {
        System.out.print("Enter a Number to check Magic Number: ");
        number = sc.nextInt();
    }
    // Check the number after adding its digits 1 or not
    public boolean isMagicNumber(int n)
    {
        int sum=0,flag,d=0;
        do
        {
            flag=0;
            while(n%10==0)
                n/=10;
            while(n%10!=0 || n>0) //Addition of the digit
            {
                sum+=(n%10);
                n/=10;
            }
            if(sum>=10)
            {
                n=sum;
                sum=0;
            }
            else
             flag=1;
        }while(flag==0);
        if(sum==1)
         return true;
        else  
         return false;
    } // end of isMagicNumber method
    // Main Method
    public static void main(String args[])
    {
        boolean value;
        MagicNumbers ob=new MagicNumbers();
        ob.input();
        value = ob.isMagicNumber(number);
        if(value)
         System.out.println(number  + " is a Magic Number");
        else
         System.out.println(number  + " is Not A Magic Number");
    }
}

output:
Enter a Number to check Magic Number: 10
10 is a Magic Number
Enter a Number to check Magic Number: 12
12 is Not A Magic Number


SHARE THIS
Previous Post
Next Post