随笔- 509  文章- 0  评论- 151  阅读- 22万 

Sqrt(x)

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 };
复制代码

 

 posted on   zhuli19901106  阅读(279)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示