• LeetCode


    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 };
  • 相关阅读:
    web测试方法总结
    APP测试点总结
    函数初识
    字符编码及文件操作
    简单购物车程序(Python)
    基本数据类型(列表,元祖,字典,集合)
    python基础
    基本数据类型(数字和字符串)
    Python入门
    操作系统
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3485744.html
Copyright © 2020-2023  润新知