Skip to content

Commit 5a99823

Browse files
committed
🚀 17-Jul-2020
1 parent c779756 commit 5a99823

File tree

3 files changed

+123
-0
lines changed

3 files changed

+123
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
Implement pow(x, n), which calculates x raised to the power n (xn).
2+
3+
Example 1:
4+
5+
Input: 2.00000, 10
6+
Output: 1024.00000
7+
Example 2:
8+
9+
Input: 2.10000, 3
10+
Output: 9.26100
11+
Example 3:
12+
13+
Input: 2.00000, -2
14+
Output: 0.25000
15+
Explanation: 2-2 = 1/22 = 1/4 = 0.25
16+
Note:
17+
18+
-100.0 < x < 100.0
19+
n is a 32-bit signed integer, within the range [−231, 231 − 1]
20+
21+
22+
23+
24+
25+
26+
27+
28+
29+
30+
31+
class Solution {
32+
public:
33+
double myPow(double x, int n) {
34+
double res=1;
35+
bool neg=false;
36+
if(n<0) neg=true;
37+
n=abs(n);
38+
while(n){
39+
if(n%2!=0){
40+
if(neg) res=res/x;
41+
else res=res*x;
42+
}
43+
x*=x;
44+
n/=2;
45+
}
46+
return res;
47+
}
48+
};

Diff for: competitive programming/leetcode/50. Pow(x, n).cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
Implement pow(x, n), which calculates x raised to the power n (xn).
2+
3+
Example 1:
4+
5+
Input: 2.00000, 10
6+
Output: 1024.00000
7+
Example 2:
8+
9+
Input: 2.10000, 3
10+
Output: 9.26100
11+
Example 3:
12+
13+
Input: 2.00000, -2
14+
Output: 0.25000
15+
Explanation: 2-2 = 1/22 = 1/4 = 0.25
16+
Note:
17+
18+
-100.0 < x < 100.0
19+
n is a 32-bit signed integer, within the range [−231, 231 − 1]
20+
21+
22+
23+
24+
25+
26+
27+
28+
29+
30+
31+
class Solution {
32+
public:
33+
double myPow(double x, int n) {
34+
double res=1;
35+
bool neg=false;
36+
if(n<0) neg=true;
37+
n=abs(n);
38+
while(n){
39+
if(n%2!=0){
40+
if(neg) res=res/x;
41+
else res=res*x;
42+
}
43+
x*=x;
44+
n/=2;
45+
}
46+
return res;
47+
}
48+
};

Diff for: mathematical/x_power_n_negative_decimal.cpp

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
double power(double x, int n) {
5+
double res=1;
6+
bool neg=false;
7+
if(n<0) neg=true;
8+
n=abs(n);
9+
while(n){
10+
if(n%2!=0){
11+
if(neg) res=res/x;
12+
else res=res*x;
13+
}
14+
x*=x;
15+
n/=2;
16+
}
17+
return res;
18+
}
19+
20+
int main(){
21+
int x, n;
22+
cin>>x>>n;
23+
// x^n
24+
cout<<double(power(x, n));
25+
26+
return 0;
27+
}

0 commit comments

Comments
 (0)