Leetcode_69_Sqrt(x)

94 篇文章 18 订阅
1 篇文章 0 订阅

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4
Output: 2
Example 2:

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.

思路:
(1)该题给你一个正整数,要求返回其平方根对于最大整数。
(2)首先考虑到使用java api中的Math类,哈哈,一行代码搞定,但是Math类的sqrt方法调用了本地方法,无法看见源码。另一种方法是使用类似二分查找的方法,对于正整数n,从判断n/2 * n/2 的值是否大于n,如果大于n,则从1到n/2范围内查找;否则从n/2到n里面查找,实现比较简单,这里就不给出了。
(3)代码实现如下所示。希望对你有所帮助。(其中java源码math类的sqrt方法的底层实现如下所示)

class Solution {
    public int mySqrt(int x) {
        return (int)Math.sqrt(x);
    }
}
package leetcode;

public class Sqrt {

    public static void main(String[] args) {
        System.err.print((int) (sqroot(8)));
    }

    static float sqroot(float m) {
        float i = 0;
        float x1 = 0.f;
        float x2 = 0.f;
        while ((i * i) <= m)
            i += 0.1;
        x1 = i;
        for (int j = 0; j < 10; j++) {
            x2 = m;
            x2 /= x1;
            x2 += x1;
            x2 /= 2;
            x1 = x2;
        }
        return x2;
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值