LeetCode算法系列:69. Sqrt(x)

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82751807

目录

 

题目描述:

算法实现

他山之石:

题目描述:

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

算法实现

总体的思路是使用二分法,但是用int long这样的数据类型总是溢出,想了一个办法,通过一次二分法找到一个小的范围,再运行二分法

class Solution {
public:
    int mySqrt(int x) {
        int i = 0, j = x;
        long long mid = x;
        long long suanz = 0;
        while(mid * mid > x)mid = mid/2;
        i = mid, j = mid * 2;
        while(i <= j){
            mid = (i + j)/2;
            suanz = mid*mid;
            if(suanz == x)return mid;
            else if(suanz > x)j = mid - 1;
            else if(suanz < x)i = mid + 1;
        }
        return j;
    }
};

他山之石:

发现已提交的答案中有类似的做法,不过使用size_t型定义数据

      size_t是一些C/C++标准在stddef.h中定义的。这个类型足以用来表示对象的大小。size_t的真实类型与操作系统有关。

在32位架构中被普遍定义为:

typedef   unsigned int size_t;

而在64位架构中被定义为:

typedef  unsigned long size_t;

        size_t在32位架构上是4字节,在64位架构上是8字节,在不同架构上进行编译时需要注意这个问题。而int在不同架构下都是4字节,与size_t不同;且int为带符号数,size_t为无符号数。

class Solution {
public:
    int mySqrt(int x) {
        size_t i = 0, j = x;
        size_t mid, suanz;
        while(i <= j){
            mid = (i + j)/2;
            suanz = mid*mid;
            if(suanz == x)return mid;
            else if(suanz > x)j = mid - 1;
            else if(suanz < x)i = mid + 1;
        }
        return j;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82751807