In this HackerRank Day 17: More Exceptions problem solution Write a Calculator class with a single method: int power(int, int). The power method takes two integers, n and p, as parameters and returns the integer result of n to power p. If either n or p is negative, then the method must throw an exception with the message: n and p should be non-negative.

HackerRank Day 17: More Exceptions problem solution

Problem solution in Python programming.

class Calculator:
    def power(self,n,p):
        if min(n,p) < 0:
            raise Exception('n and p should be non-negative')
        else:
            return (n**p)



Problem solution in Java programming.

//Write your code here
class Calculator{
    static int power(int n, int p) throws Exception{
        if(n<0 || p<0)
        {
            throw new Exception("n and p should be non-negative");
        }
        else
            return (int)Math.pow(n,p);
    }
}




Problem solution in C++ programming.

//Write your code here
class myexception : public exception{
 virtual const char* what() const throw(){
    return "n and p should be non-negative" ;
 }   
} myex;

class Calculator{
   public:
    int power(int n, int p){
       if(n<0 || p < 0){
           throw myex;
       }
      return pow(n,p);
   }
};



Problem solution in Javascript programming.

//Write your code here
function Calculator() {
    this.power = (n, p) => {
        if (n < 0 || p < 0) {
            throw 'n and p should be non-negative';
        }
        
        return Math.pow(n, p);
    };
}