首先我想说这题太坑了,如果你先判断是奇数不是偶数,对不起通过不了。
AC:
class Solution {
public:
double ExponentUnsignRes(double base, int n)
{
if (n == 0)return 1.0;
if (n == 1)return base;
double res = ExponentUnsignRes(base, n/2);
if (n %2 == 0)
return res*res;
else
return res*res*base;
}
double myPow(double x, int n) {
if (n < 0)
return 1.0 / ExponentUnsignRes(x,-n);
return ExponentUnsignRes(x, n);
}
};
不能Ac:
double res = ExponentUnsignRes(base, n/2);
if (n %2 == 0)
只要这两句改成等价的语句就通过不了,例如:
double res = ExponentUnsignRes(base, n>>1);
if (n & 0x1 == 0)
或者:
double res = ExponentUnsignRes(base, n/2);
if (n %2 == 1)
return res*res*base;
else
return res*res;
思考:
为什么先算奇数就有反例 。
后来在讨论区里发现:
其实上面的逻辑都是对的,当你加上这句if(n == INT_MIN) return x == 1.0 || x == -1.0 ? 1.0 : 0.0;
时怎么变换逻辑形式都能通过。比如Ac:
class Solution {
public:
double ExponentUnsignRes(double base, int n)
{
if (n == 0)return 1.0;
if (n == 1)return base;
double res = ExponentUnsignRes(base, n>>1);
if (n & 0x1 == 1)
return res*res*base;
else
return res*res;
}
double myPow(double x, int n) {
if(n == INT_MIN) return x == 1.0 || x == -1.0 ? 1.0 : 0.0; // 没有这一句无法通过
if (n < 0)
return 1.0 / ExponentUnsignRes(x,-n);
return ExponentUnsignRes(x, n);
}
};
官方的测试用例坑坑坑!
欢迎指正!