2013.12.17 13:56
Implement pow(x, n).
Solution:
Problem description is simple, so is the solution: divide and conquer. To calculae x^n, you'll need to know x^(n / 2) first.
Later, let's deal with boundary values:
1. n = 0
2. n > 0
3. n < 0
4. x < 0
5. x = 0.0 (IEEE754 zero)
6. x > 0
Think of any possible combinations and use your code for complete path coverage.
Time complexity is O(log(n)), space complexity is also O(log(n)).
Accepted code:
1 // 3RE, 1WA, 1AC 2 class Solution { 3 public: 4 double pow(double x, int n) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 if(x == 0.0){ 8 return 0; 9 } 10 11 // 1RE here, special case of x = 1 12 if(x == 1.0){ 13 return 1.0; 14 } 15 16 // 1RE, special case of x < 0 17 if(x < 0){ 18 if(n % 2 == 1){ 19 return -pow(-x, n); 20 }else{ 21 return pow(-x, n); 22 } 23 } 24 25 // 1RE, should be $n, wrote $x 26 if(n < 0){ 27 return pow(1.0 / x, -n); 28 }else if(n == 0){ 29 return 1.0; 30 }else if(n == 1){ 31 return x; 32 }else{ 33 if(n % 2 == 1){ 34 // 1WA here, pow(x * x, n / 2) is wrong 35 double res = pow(x, n / 2); 36 return x * res * res; 37 }else{ 38 double res = pow(x, n / 2); 39 return res * res; 40 } 41 } 42 } 43 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)