本文共 844 字,大约阅读时间需要 2 分钟。
Implement pow(x, n).
主要利用x^2n = (x^n)*(x^n), x^2n+1 = (x^n)*(x^n)*x
注意n是负数,对其取反时,可能会溢出
其实0^0(都是整数)是未定义的,因为0^0 = 0^1 / 0^1 = 0 / 0, 0作为除数是未定义的,可以参考。
但是库函数pow(0.0,0) = 1,下面我们也这么处理。
如果x是无穷大(即x = numeric_limits<double>::infinity()),如果n>0,返回无穷大,如果n == 0返回1,如果n<0,返回负无穷-numeric_limits<double>::infinity()。(1/0.0 不会出现运行错误,结果是正无穷)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Solution { public : double pow ( double x, int n) { //基数为1,-1, 0,可以特殊处理 //if(x == 1)return 1.0; //else if(x == -1)return n%2 ? -1.0 : 1.0; //else if(x == 0)return 0.0; double res = 1.0; //使用long long主要防止n = -2147483648时,取反溢出 long long nn = n; if (nn < 0) nn = -nn; while (nn != 0) { if (nn & 1) res *= x; nn >>= 1; x *= x; } if (n > 0) return res; else return 1/res; } }; |