leetcode题记:Sqrt(x)

编程语言:JAVA

题目描述:

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.

提交反馈:

1017 / 1017 test cases passed.
Status: Accepted
Runtime: 22 ms
Submitted: 0 minutes ago
You are here! 
Your runtime beats 80.32 % of java submissions.

解题思路:

二分法。被JAVA的int与long坑了,刚开始提交报错发现int溢出,然后决定改为long,就OK。另外,java没有无符号整数。

理论上,int表示最大2的32次(int占用4个字节),long最大表示2的64次(long占用8个字节),这样2的32次的平方也小于2的64次,不会溢出的啊,懵逼。。。经查询,发现这个long是带符号的,并且java没有无符号的整数。。。

参考链接:[java中 long 和double的区别](https://blog.csdn.net/qq_34789775/article/details/71153161)

还有一种思路就是:

    不要写成middle*middle==x,会溢出
    写成这样的,if(middle==x/middle)

代码:

class Solution {
    public int mySqrt(int x) {

        if(x == 0){
            return 0;
        }
        if(x == 1){
            return 1;
        }

        long left = 1;
        long right = x;
        double middle; //不能为int或者long,因为long为无符号整数,当x很大时候会出现负数。

        while(right - left > 1){
            middle = (left + right)/2;
            double dot = middle * middle;
            if(dot > x){
                right = (long)middle;
            }
            else if(dot < x){
                left = (long)middle;
            }
            else{
                return (int)middle;
            }
        }
        return (int)left;
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页