shell33168
shell33168
2017-11-08 04:24

Sqrt(x) 求一个数的开方

  • 算法
  • square
  • java

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

 class Solution {
    public int mySqrt(int x) 
    {
        int j=0;
        if(x==1)
        {
            j=1;
        }else{
             for(int i=1;i<x;i++)
             {
                if(x>=i*i && x<(i+1)*(i+1))
                {
                    j=i;
                    break;
                }
             }
        }
        return j;
    }
}

为什么代码小数值算出的结果都是对的,到 2147395600 结果就错了?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐