Page 426 - Computer science 868 Class 12
P. 426

D.  Long answer type questions/programs:
                  1.  Design a class Unique to check if a given number is Unique number or not. Unique numbers have no repeating digits in it. The
                    details are given below:
                     Class Name                                :  Unique
                     Data Member
                     int n                                     :  To store number
                     Member methods
                     Unique(int a)                             :  Constructor to assign n = a
                     int count(int d, int a)                   :    Counts and returns how many times digit 'd' occurs in numbers 'a'
                                                                 using recursion
                     void check()                              :  Calls count(int, int) and prints if the number is unique or not
                     Define  the class giving details  of the methods  given above. Also,  write  the main method  to create  object and call  other
                    methods.

                Ans.  class Unique
                    {
                      int n;
                      Unique(int a)
                      {
                      n = a;
                      }
                      int count(int d, int a)
                      {
                      if (a == 0) //base case
                        return 0;
                      else if (a%10==d) //if digit exists
                        return 1+count(d, a/10); //recursive case
                    else
                        return count(d, a/10); //if digit does not exist
                    }
                    void check()
                    {int c;
                        for(int i=0; i<=9; i++)
                        {
                              c=count(i, n); //calling method
                              if(c>1)
                                  break;
                        }
                        if(c>1)
                              System.out.println(n+ "is not unique");
                        else
                              System.out.println(n+ "is unique");
                        }
                        public static void main(int x)
                        {
                              Unique ob=new Unique(x);
                              ob. check();
                              }
                        }
                    }

                424424  Touchpad Computer Science-XII
   421   422   423   424   425   426   427   428   429   430   431