|
| 1 | +package com.leetcode.arrays.binarysearch; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | + |
| 5 | +/** |
| 6 | + * Level: Medium |
| 7 | + * Link: https://leetcode.com/problems/powx-n/ |
| 8 | + * Description: |
| 9 | + * Implement pow(x, n), which calculates x raised to the power n (x^n). |
| 10 | + * <p> |
| 11 | + * Example 1: |
| 12 | + * Input: 2.00000, 10 |
| 13 | + * Output: 1024.00000 |
| 14 | + * <p> |
| 15 | + * Example 2: |
| 16 | + * Input: 2.10000, 3 |
| 17 | + * Output: 9.26100 |
| 18 | + * <p> |
| 19 | + * Example 3: |
| 20 | + * Input: 2.00000, -2 |
| 21 | + * Output: 0.25000 |
| 22 | + * Explanation: 2^-2 = 1/22 = 1/4 = 0.25 |
| 23 | + * <p> |
| 24 | + * Note: |
| 25 | + * -100.0 < x < 100.0 |
| 26 | + * n is a 32-bit signed integer, within the range [−231, 231 − 1] |
| 27 | + * |
| 28 | + * @author rampatra |
| 29 | + * @since 2019-08-19 |
| 30 | + */ |
| 31 | +public class PowXN { |
| 32 | + |
| 33 | + /** |
| 34 | + * In this approach we iterate n times and keep multiplying x with x. |
| 35 | + * Runtime: <a href="https://leetcode.com/submissions/detail/253075786/">Time limit exceeded</a>. |
| 36 | + * |
| 37 | + * @param x |
| 38 | + * @param n |
| 39 | + * @return |
| 40 | + */ |
| 41 | + public static double myPowNaive(double x, int n) { |
| 42 | + if (n == 0) { |
| 43 | + return 1; |
| 44 | + } |
| 45 | + double res = x; |
| 46 | + int absN = Math.abs(n); |
| 47 | + for (int i = 1; i < absN; i++) { |
| 48 | + res *= x; |
| 49 | + } |
| 50 | + return n < 0 ? 1 / res : res; |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + /** |
| 55 | + * In this approach, we iterate log n times. We omit half of n each time. When n is odd, we store whatever product |
| 56 | + * we have calculated so far in the final result. |
| 57 | + * <p> |
| 58 | + * Runtime: <a href="https://leetcode.com/submissions/detail/253276630/">1 ms</a>. |
| 59 | + * |
| 60 | + * @param x |
| 61 | + * @param n |
| 62 | + * @return |
| 63 | + */ |
| 64 | + public static double myPow(double x, int n) { |
| 65 | + double res = 1; |
| 66 | + long absN = Math.abs((long) n); |
| 67 | + |
| 68 | + while (absN > 0) { |
| 69 | + if (absN % 2 == 1) res *= x; // store whatever we have calculated so far in the final result |
| 70 | + x *= x; |
| 71 | + absN /= 2; |
| 72 | + } |
| 73 | + return n < 0 ? 1 / res : res; |
| 74 | + } |
| 75 | + |
| 76 | + public static void main(String[] args) { |
| 77 | + assertEquals(1024.0, myPowNaive(2.0, 10)); |
| 78 | + assertEquals(0.25, myPowNaive(2.0, -2)); |
| 79 | + assertEquals(0.0, myPowNaive(0.00001, 2147483647)); |
| 80 | + |
| 81 | + assertEquals(1024.0, myPow(2.0, 10)); |
| 82 | + assertEquals(0.25, myPow(2.0, -2)); |
| 83 | + assertEquals(0.0, myPow(0.00001, 2147483647)); |
| 84 | + } |
| 85 | +} |
0 commit comments