Recent Post

Accessing Inherited Functions.cpp-HackerRank

Problem-You are given three classes A, B and C. All three classes implement their own version of func.

In class Afunc multiplies the value passed as a parameter by :

class A
{
public:
A(){
callA = 0;
}
private:
int callA;
void inc(){
callA++;
}

protected:
void func(int & a)
{
a = a * 2;
inc();
}
public:
int getA(){
return callA;
}
};

In class Bfunc multiplies the value passed as a parameter by :

class B
{
public:
B(){
callB = 0;
}
private:
int callB;
void inc(){
callB++;
}
protected:
void func(int & a)
{
a = a * 3;
inc();
}
public:
int getB(){
return callB;
}
};

In class Cfunc multiplies the value passed as a parameter by :

class C
{
public:
C(){
callC = 0;
}
private:
int callC;
void inc(){
callC++;
}
protected:
void func(int & a)
{
a = a * 5;
inc();
}
public:
int getC(){
return callC;
}
};

You are given a class D:

class D
{

int val;
public:
//Initially val is 1
D()
{
val = 1;
}
//Implement this function
void update_val(int new_val)
{
}
//For Checking Purpose
void check(int); //Do not delete this line.
};

You need to modify the class D and implement the function update_val which sets D's val to new_val by manipulating the value by only calling the func defined in classes A, B and C.


Solution-

class D : public A,public B,public C
{
 int val;
  public:
   D()
   {
    val=1;
   }
   void update_val(int new_val)
   {
          int a = new_val;
     while ( a %2 == 0)
     {
         a = a/2;
         A::func(val);
     }
     while ( a % 3 == 0)
     {
         a = a/3;
         B::func(val);
     }
     while ( a % 5 == 0)
     {
         a = a/5;
         C::func(val);
     }
   
   }
   void check(int);
};

Link to the problem:-

Result!

Comments

Popular posts from this blog

Caesar Cipher.c-HackerRank

Bon Appétit.c-HackerRank

Electronics Shop.c-HackerRank