Leetcode x的平方根

x的平方根

题目描述:

实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

题目链接

class Solution {
    
    
    public int mySqrt(int x) {
    
    
        for(int i = 1 ; i<x ; i++){
    
    
            if(i*i > x || i*i < 0){
    
     // 大于x或者整型溢出
                return (i-1);
            }
        }
        if(x == 0 || x == 1) return x;
        else{
    
    
            return 1;
        }
    }
}

按照题意即可。

猜你喜欢

转载自blog.csdn.net/weixin_43914658/article/details/113804483