【LeetCode】69.x的平方根

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/ca1m0921/article/details/89608764

leetCode 题目描述:

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 x 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例 1:

输入: 4
输出: 2
示例 2:

输入: 8
输出: 2
说明: 8 的平方根是 2.82842..., 
     由于返回类型是整数,小数部分将被舍去。

我的解法: 

class Solution {
    public int mySqrt(int x) {
        if(x == 0){ 
			return 0;
		}
		int result = (int)Math.pow(10,(String.valueOf(x).length()/2));
		int begin = 0,end = x;
		int count = 0;
		for(int i = 0; i < x; i++){	
			count ++;
			if(begin == end - 1 || (Math.pow(result, 2)) == x){
				break;
			}
			if((Math.pow(result, 2)) < x){
				begin = result;
				result = (result + end)/2;
			}else{
				end = result;
				result = (begin + result)/2;
			}
		}
		return result;
    }
}

思路: 总觉得 x/2 会比较小。所以使用了 转 string,确定位数折半的方法,直接取个何时的值。例如 10000 直接取 100。

这样的话,下一次在 begin -- result 或者  result --- end之间取值,感觉很合理。

需要注意的是 : 第一次 提交代码,没有考虑 0的问题,当时只看到了 负整数,忘了0,尴尬。

 第二次 提交代码,没有考虑 begin == end-1 陷入死循环,对于编程中的 除法 四舍五入原则不太清楚。

评级:

就这样了。

猜你喜欢

转载自blog.csdn.net/ca1m0921/article/details/89608764