Skip to content

Commit

Permalink
problem 50
Browse files Browse the repository at this point in the history
  • Loading branch information
Deepanshuchauhan123 committed Apr 18, 2021
1 parent 8765330 commit 45802fe
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions LeetCode Practice/Problem_50_power.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.util.Scanner;

class Problem_50_power{
static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
try {
long power;
double base;
System.out.println("Enter Base = ");
base = sc.nextDouble();
System.out.println("Enter power = ");
power = sc.nextLong();
System.out.println(power_calculation(base, power));
} catch (Exception e) {
e.printStackTrace();
}

}

static double power_calculation(double x, long n) {
double value = 1;
boolean negative = false;
if (n < 0) {
negative = true;
n = -n;
}
while (n > 0) {
if (n % 2 == 0) {
x = x * x;
n /= 2;
} else {
value = value * x;
n--;
}
}
if (negative)
value = 1 / value;
return value;
}
}

0 comments on commit 45802fe

Please sign in to comment.