2013.12.22 04:02
Implement int sqrt(int x)
.
Compute and return the square root of x.
Solution 1:
The square root can be calculated using a binary iteration, with an initial interval of [1, x - 1].
Time complexity is O(log2(x)), space complexity is O(1).
Accepted code:
1 // 2WA, 1AC, binary search + long long int 2 class Solution { 3 public: 4 int sqrt(int x) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 long long int xx = x; 8 9 if(x <= 0){ 10 return 0; 11 }else if(x < 4){ 12 return 1; 13 } 14 15 long long int ll, rr, mm; 16 ll = 1; 17 rr = xx - 1; 18 while(rr - ll > 1){ 19 mm = (ll + rr) / 2; 20 // 1WA here, wrong side of '<' 21 if(xx < mm * mm){ 22 rr = mm; 23 }else{ 24 ll = mm; 25 } 26 } 27 28 // 1WA here, return $ll, not $rr 29 return ll; 30 } 31 };
Solution 2:
Actually there is no need to use long long int to avoid integer overflow, since "xx < mm * mm" can be replaced with "x / mm < mm".
Integer underflow is usually safer than overflow, especially when it converges to 0, that's why we use it for some convenience.
Time complexity is O(log2(x)), space complexity is O(1).
Accepted code:
1 // 1AC, integer overflow can be avoided by using '/' instead of '*'. 2 class Solution { 3 public: 4 int sqrt(int x) { 5 if(x <= 0){ 6 return 0; 7 }else if(x < 4){ 8 return 1; 9 } 10 11 long long int ll, rr, mm; 12 ll = 1; 13 rr = x - 1; 14 while(rr - ll > 1){ 15 mm = (ll + rr) / 2; 16 if(x / mm < mm){ 17 rr = mm; 18 }else{ 19 ll = mm; 20 } 21 } 22 23 return ll; 24 } 25 };
【推荐】国内首个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新功能体验(一)