forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pow.cpp
45 lines (38 loc) · 866 Bytes
/
pow.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Source : https://oj.leetcode.com/problems/powx-n/
// Author : Hao Chen
// Date : 2014-06-25
/**********************************************************************************
*
* Implement pow(x, n).
*
*
**********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
double pow(double x, int n) {
bool sign = false;
unsigned int exp = n;
if(n<0){
exp = -n;
sign = true;
}
double result = 1.0;
while (exp) {
if (exp & 1){
result *= x;
}
exp >>= 1;
x *= x;
}
return sign ? 1/result : result;
}
int main(int argc, char** argv){
double x=2.0;
int n = 3;
if (argc==3){
x = atof(argv[1]);
n = atoi(argv[2]);
}
printf("%f\n", pow(x, n));
return 0;
}