首页 > 其他 > 详细

LeetCode-- Implement int sqrt(int x)

时间:2015-12-02 10:36:52      阅读:257      评论:0      收藏:0      [点我收藏+]
题目描述:


Implement int sqrt(int x).


Compute and return the square root of x.


求一个整数的完全平方数,但返回的是Int。


从n/2开始递减,找到 i*i == n,注意int溢出的处理(从Sqrt(int.MaxValue)开始递减)




实现代码:




public class Solution {
    public int MySqrt(int x) {
    if(x < 2){
	    return x;
	}
	if(x > int.MaxValue){
		x = int.MaxValue;
	}
	
	var half = 46340; // Sqrt(int.MaxValue)
	
	for(var i = half; i >= 1; i--){
		if(i * i == x){
			return i;
		}
		if(i * i < x){
			return i;
		}
	}
	
	return -1;
    }
}


LeetCode-- Implement int sqrt(int x)

原文:http://blog.csdn.net/lan_liang/article/details/50144615

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!