50. Pow(x, n)官方的测试用例有坑

首先我想说这题太坑了,如果你先判断是奇数不是偶数,对不起通过不了。
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);
	 }
 };

官方的测试用例坑坑坑!

欢迎指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值