LeetCode POW

 1     double pow(double x, int n) {
 2         if (n == 0) return 1;
 3         unsigned int k = 0;
 4         if (n < 0) {
 5             x = 1.0 / x;
 6             k = -n;
 7         } else {
 8             k = n;
 9         }
10         if (k == 1) return x;
11         
12         double r = pow(x, k/2);
13         r = r * r;
14         if (0x1 & k) {
15             r = r * x;
16         }
17         return r;
18     }
 1 double pow(double x, int n) {
 2         unsigned int k = 0;
 3         if (n < 0) {
 4             k = -n;
 5             x = 1.0 / x;
 6         } else {
 7             k = n;
 8         }
 9         double ret = 1;
10         while (k != 0) {
11             if (k & 0x1) ret *= x;
12             x *= x; 
13             k>>=1;
14         }
15         return ret;
16     }

MS 2012 math.h

 1 template<class _Ty> inline
 2         _Ty _Pow_int(_Ty _X, int _Y)
 3         {unsigned int _N;
 4         if (_Y >= 0)
 5                 _N = (unsigned int)_Y;
 6         else
 7                 _N = (unsigned int)(-_Y);
 8         for (_Ty _Z = _Ty(1); ; _X *= _X)
 9                 {if ((_N & 1) != 0)
10                         _Z *= _X;
11                 if ((_N >>= 1) == 0)
12                         return (_Y < 0 ? _Ty(1) / _Z : _Z); }}

 

 

 

posted @ 2014-03-11 14:39  卖程序的小歪  阅读(147)  评论(0编辑  收藏  举报