Hacker Rank - Day 17 : More Exceptions

                   Day 17 : More Exceptions

Solution In Java 8:


import java.util.*;
import java.io.*;

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

class Solution{

    public static void main(String []argh)
    {
        Scanner in = new Scanner(System.in);
        int T=in.nextInt();
        while(T-->0)
        {
            int n = in.nextInt();
            int p = in.nextInt();
            Calculator myCalculator = new Calculator();
            try
            {
                int ans=myCalculator.power(n,p);
                System.out.println(ans);
               
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        }

    }
}
 


Solution In Python 3: 
class Calculator(Exception):
    def power(self,n,p):
        self.n = n
        self.p = p
        if self.n < 0 or self.p < 0:
            raise Exception("n and p should be non-negative")

        return self.n**self.p
myCalculator=Calculator()
T=int(input())
for i in range(T):
    n,p = map(int, input().split())
    try:
        ans=myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)  
Share:

0 comments:

Post a Comment