Skip to content

Commit

Permalink
Pow
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 21, 2017
1 parent ef43871 commit d0fe9c1
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion 050_pow/pow.c
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

/*
* n == 2(10) -- 2 -- res = 1 * 2^2
* n == 3(11) -- 2 + 1 -- res = 1 * 2^1 * 2^2
* n == 4(100) -- 4 -- res = 1 * 2^4
* n == 5(101) -- 4 + 1 -- res = 1 * 2^1 * 2^4
* n == 6(110) -- 4 + 2 + 1 -- res = 1 * 2^1 * 2^2 * 2^4
*/
static double my_pow(double x, int n)
{
int orig = x;
int sign = 0;
int one_more = 0;
if (n < 0) {
n = -n;
if (n == INT_MIN) {
n = INT_MAX;
one_more = 1;
} else {
n = -n;
}
sign = 1;
}

Expand All @@ -17,6 +32,9 @@ static double my_pow(double x, int n)
x *= x;
n >>= 1;
}
if (one_more) {
res *= orig;
}

return sign ? 1 / res : res;
}
Expand Down

0 comments on commit d0fe9c1

Please sign in to comment.