We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Day 17: More Exceptions
Day 17: More Exceptions
+ 0 comments Java 7:
class Calculator { int power(int n, int p) throws Exception { int sum = 1; if(n >= 0 && p >= 0) { for(int i = 0; i < p; i++) sum *= n; } else { throw new Exception("n and p should be non-negative"); } return sum; } }
+ 0 comments My solution in Java
import java.io.*; import java.util.*; 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"); }else{ return (int)Math.pow(n,p); } } } public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Calculator calculate = new Calculator(); int testCases = Integer.parseInt(scan.nextLine().trim()); while(testCases > 0){ String[] inputArray = scan.nextLine().trim().split(" "); int n = Integer.parseInt(inputArray[0]); int p = Integer.parseInt(inputArray[1]); try{ int result = calculate.power(n, p); System.out.println(result); }catch(Exception ex){ System.out.println(ex.getMessage()); } testCases--; } } }
+ 0 comments Python 3
class Calculator(): def power(self, n, p): if n<0 or p<0: raise Exception("n and p should be non-negative") return n**p
+ 0 comments Py3:
Write your code here
class Error(Exception): def init(self): super().init("n and p should be non-negative")
class Calculator(): def power(self,n,p): if n<0 or p<0: raise Error else: return n**p
+ 0 comments Python 3
btw no raise Exception needed to pass test
class Calculator: def power(self, n, p): return n ** p if n >= 0 and p >= 0 else \ 'n and p should be non-negative'
Load more conversations
Sort 604 Discussions, By:
Please Login in order to post a comment