-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathpow.cpp
More file actions
37 lines (36 loc) · 739 Bytes
/
pow.cpp
File metadata and controls
37 lines (36 loc) · 739 Bytes
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
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 11, 2012
Problem: pow(x, n)
Difficulty: medium
Source: http://www.leetcode.com/onlinejudge
Notes:
Implement pow(x, n).
Solution:
Be careful about the boundry test and write neat expontential step
algorithm to avoid TLE.
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
class Solution {
public:
double pow(double x, int n) {
double result = 1.0;
double step = x;
for (int i = abs(n); i > 0; i /= 2) {
if (i & 1) {
result *= step;
}
step *= step;
}
result = (n < 0 ? 1 / result : result);
return result;
}
};