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

Sqrt(x)

时间:2015-08-01 22:06:03      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:c++dlllib   leetcode   搜索   

Question

Implement int sqrt(int x).

Compute and return the square root of x.

My Solution

class Solution {
public:
	int mySqrt(int x) {
		/**
		* binary search a from [0, x], where a^2 = x.
		*/
		if (x < 0) return 0;
		return BSearchByLoop(x);
	}

	int BSearch(int x, int start, int end) {
		/**
		* binary search a from [start, end], where a^2 = x.
		* Note: when x is very big, stack overflow exception occurs.
		*
		* 1. if start > end, then return -1;
		* 2. tmp = (start + end) / 2
		* 3. if tmp^2 = x, then return tmp;
		* 4. if tmp^2 < x, then return BSearch(x, tmp + 1, end);
		* 5. if tmp^2 > x, then return BSearch(x, start, tmp - 1);
		*/

		if (0 == x || 1 == x) return x;

		if (start >= end) {
			if (start * start <= x) return start;
			else return start - 1;
		}

		int mid = (start + end) / 2;
		if (mid * mid == x) return mid;
		else if (mid * mid < x) return BSearch(x, mid + 1, end);
		else return BSearch(x, start, mid - 1);
	}

	int BSearchByLoop(int x)
	{
		/*
		1. if 0 == x or 1 == x, then return x;
		2. start = 0, end = x.
		3. if start > end, then return end;
		4. mid = (start + end) / 2;
		5. if mid^2 == x, return mid;
		6. if mid^2 > x, end = mid - 1; jmp 3;
		7. if mid^2 < x, start = mid + 1; jmp 3;
		*/

		if (0 == x || 1 == x) return x;
		int start = 0, end = x;
		while (start <= end)
		{
			long long mid = (end - start) / 2 + start; // mid*mid is probably bigger than 2^32
			if (mid * mid == x) return mid;
			else if (mid * mid > x) end = mid - 1;
			else start = mid + 1;
		}
		return end;
	}
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

Sqrt(x)

标签:c++dlllib   leetcode   搜索   

原文地址:http://blog.csdn.net/u012365383/article/details/47190067

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!