TheBulgarianWolf

More Exceptions Hackerrank

May 24th, 2021
837
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.96 KB | None | 0 0
  1. using System;
  2.  
  3. //Write your code here
  4. public class Calculator{
  5.     public int power(int n,int p){
  6.         int sum = 1;
  7.         if(n < 0 || p < 0){
  8.             throw new Exception("n and p should be non-negative");
  9.         }
  10.         else {
  11.             while(p > 0){
  12.                 sum *= n;
  13.                 p--;
  14.             }
  15.         }
  16.         return sum;
  17.     }
  18. }
  19.  
  20. public class Solution{
  21.     public static void Main(String[] args){
  22.         Calculator myCalculator=new  Calculator();
  23.         int T=Int32.Parse(Console.ReadLine());
  24.         while(T-->0){
  25.             string[] num = Console.ReadLine().Split();
  26.             int n = int.Parse(num[0]);
  27.             int p = int.Parse(num[1]);
  28.             try{
  29.                 int ans=myCalculator.power(n,p);
  30.                 Console.WriteLine(ans);
  31.             }
  32.             catch(Exception e){
  33.                Console.WriteLine(e.Message);
  34.  
  35.             }
  36.         }
  37.        
  38.        
  39.        
  40.     }
  41. }
Add Comment
Please, Sign In to add comment