-
Notifications
You must be signed in to change notification settings - Fork 30
/
Powxn.cs
executable file
·69 lines (65 loc) · 3.54 KB
/
Powxn.cs
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Source : https://leetcode.com/problems/powx-n/
// Author : codeyu
// Date : Tuesday, October 25, 2016 11:21:24 PM
/**********************************************************************************
*
* Implement pow(x, n).
*
*
**********************************************************************************/
using System;
using System.Collections.Generic;
using Algorithms.Utils;
namespace Algorithms
{
public class Solution050
{
public static double MyPow(double x, int n)
{
if(n == 0) return 1.0;
var ans = 1.0;
var i = Math.Abs(n);
while( i > 0)
{
ans *= x;
i--;
}
return n > 0 ? ans : 1.0 / ans;
}
public static double MyPow2(double x, int n)
{
if(n == 0) return 1.0;
var ans = 1.0;
if(n<0)
{
if(x >= 1.0/Double.MaxValue || x <= 1.0/-Double.MaxValue)
x = 1.0/x;
else
return Double.MaxValue;
if(n==int.MinValue)
{
ans *= x;
n++;
}
}
n = Math.Abs(n);
bool isNeg = false;
if(n % 2 == 1 && x < 0)
{
isNeg = true;
}
x = Math.Abs(x);
while(n > 0)
{
if((n & 1) == 1)
{
if(ans > Double.MaxValue / x) return Double.MaxValue;
ans = ans * x;
}
x = x * x;
n >>= 1; //快速幂
}
return isNeg ? -ans : ans;
}
}
}