shell33168 2017-11-08 04:24 采纳率: 0%
浏览 1318

Sqrt(x) 求一个数的开方

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条回答 默认 最新

  • shell33168 2017-11-08 04:25
    关注
     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;
        }
    }
    
    评论

报告相同问题?