Last active
February 25, 2017 21:52
-
-
Save xiaq/c999f463db31002c78ff2eacd2bc9c51 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Solution { | |
| public double myPow(double x, int n) { | |
| if (n < 0 && -n < 0) { | |
| n /= 2; | |
| x *= x; | |
| } | |
| if (n < 0) { | |
| n = -n; | |
| x = 1 / x; | |
| } | |
| // Loop invariant: | |
| // At the beginning of the j-th (0-based) iteration, y = x to the power of n', where n' is the first j digits of n. | |
| // Alternatively: | |
| // At the end of each iteration, y = x to the power of n >> i. | |
| double y = 1; | |
| for (int i = Integer.SIZE-1; i >= 0; i--) { | |
| y *= y; | |
| if ((n & (1 << i)) != 0) { | |
| y *= x; | |
| } | |
| } | |
| return y; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment