码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-- Implement int sqrt(int x)

时间:2015-12-02 10:36:55      阅读:82      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!