50. Pow(x, n) [LeetCode]

版权声明:QQ:872289455. WeChat:luw9527. https://blog.csdn.net/MC_007/article/details/81214891

Implement pow(xn), which calculates x raised to the power n (xn).

//二分法x^n=x^(n/2)*x^(n/2)*x^(n%2)
//分治法
class Solution {
public:
	double myPow(double x, int n) {
		if (n < 0)return power(x, -n);
		else return power(x, n);
	}
private:
	double power(double x, int n) {
		if (n == 0)return 1;
		double v = power(x, n / 2);
		if (n % 2 == 0)return v * v;
		else return v * v*x;
	}
};

69. Sqrt(x)


Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.
//分治法
class Solution_1 {
public:
	int mySqrt(int x) {
		if (x<2)return x;
		int left = 1;
		int right = x / 2;
		int last_mid;//记录最近一次mid

		while (left <= right) {
			const int mid = left + (right - left) / 2;
			if (x / mid>mid) {//不要使用x>mid*mid,会溢出
				last_mid = mid;
				left = mid + 1;
			}
			else if (x / mid<mid)
				right = mid - 1;
			else
				return mid;
		}
		return last_mid;
	}
};


class Solution_2 {
public:
	int mySqrt(int x) {
		if (x<2)return x;
		int left = 1, right = INT_MAX;
		while (true) {
			int mid = left + (right - left) / 2;
			if (mid > x / mid) {
				right = mid - 1;
			}
			else {
				if (mid + 1 > x / (mid + 1))
					return mid;
				left = mid + 1;
			}
		}
	}
};

猜你喜欢

转载自blog.csdn.net/MC_007/article/details/81214891