We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a9b9f5f commit 6c4bc07Copy full SHA for 6c4bc07
1 file changed
LeetCode/pow.java
@@ -0,0 +1,34 @@
1
+//Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
2
+//example input 2 2
3
+//output = 4
4
+
5
+//exmple input 2 10
6
+//output = 1024
7
8
9
10
+import java.util.*;
11
+public class POW {
12
+ static int pwr(int x, int n)
13
+ {
14
+ //if power is zero return 1
15
+ if (n == 0)
16
+ return 1;
17
+ else if (n % 2 == 0)
18
+ // lwt if x = 2 & n = 8 which is divisible by 2 - returns 2^4 * 2^4 = 2^8
19
+ return pwr(x, n / 2) * pwr(x, n / 2);
20
+ else
21
+ return x * pwr(x, n / 2) * pwr(x, n / 2);
22
+ //if n = 7 returns 2*(2^3 * 2^3) = 2^7
23
+ }
24
25
+ public static void main(String[] args)
26
27
+ //take input x,n
28
+ Scanner sc = new Scanner(System.in);
29
+ int x = sc.nextInt();
30
+ int n = sc.nextInt();
31
32
+ System.out.printf("%d", pwr(x, n));
33
34
+}
0 commit comments