Sqrt(x)

来源:互联网 发布:华为网络机顶盒插上u盘 编辑:程序博客网 时间:2024/05/17 03:17

Implement int sqrt(int x).

Compute and return the square root of x.

public class Solution {    public int sqrt(int x) {// Start typing your Java solution below// DO NOT write main() function// Newton's methodif(x == 0)return 0;double val = x;double last;do{last = val;val = (val + x / val) / 2;}while(Math.abs(val - last) > 0.000001);return (int)val;}}


Another solution

public int sqrt2(int x) {long i = 0;long j = x / 2 + 1;while (i <= j) {long mid = (i + j) / 2;long sq = mid * mid;if (sq == x)return (int)mid;else if (sq < x)i = mid + 1;elsej = mid - 1;}return (int)j;}


原创粉丝点击