More exeception problem solution 30 days of code HackerRank

Input Format
Input from stdin is handled for you by the locked stub code in your editor. The first line contains an integer, , the number of test cases. Each of the  subsequent lines describes a test case in  space-separated integers denoting  and , respectively.
Constraints
  • No Test Case will result in overflow for correctly written code.
Output Format
Output to stdout is handled for you by the locked stub code in your editor. There are  lines of output, where each line contains the result of  as calculated by your Calculator class' power method.
More exeception problem solution 30 days of code HackerRank

Problem solution in Java programming language.

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

Second solution

class Calculator{
    public 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);
    }
}

Problem solution in Ruby programming language.

class Calculator
    def power(n, p)
        if n < 0 or p < 0
            raise RangeError, "n and p should be non-negative"
        else
            return n**p
        end
    end
end

Problem solution in Python programming language.

#Write your code here
class Calculator:

    def power(self,n, p):
        if n < 0 or p < 0:
            raise Exception("n and p should be non-negative")
        else:
            return pow(n,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)   

Post a Comment

0 Comments