380. Calculate Number Power Without Built-In Functions
Calculate Power Without Built-In Functions
Given a number and an integer exponent, calculate the number raised to that exponent without using a built-in power function.

Calculate Number Power

Implement the following method:
double calculatePower(double base, int exponent)
  • base is the number to be raised.
  • exponent is the power applied to the number.
  • The method returns base raised to exponent.

Rules

  • A positive exponent multiplies the base repeatedly.
  • A negative exponent returns the reciprocal of the corresponding positive power.
  • An exponent of 0 returns 1.0.
  • Built-in power functions must not be used.

Constraints

  • -100.0 < base < 100.0
  • -2,147,483,648 ≤ exponent ≤ 2,147,483,647
  • If exponent < 0, then base ≠ 0.
  • The result fits in a double.

Examples

Example 1

calculatePower(base = 2.5, exponent = 3)
Output: 15.625

Example 2

calculatePower(base = -2.0, exponent = 4)
Output: 16.0

Example 3

calculatePower(base = 4.0, exponent = -2)
Output: 0.0625

Example 4

calculatePower(base = 8.3, exponent = 0)
Output: 1.0


Please use Laptop/Desktop or any other large screen to add/edit code.