50. Pow(x, n)
Implement pow(x, n).
简单粗暴的题目解释【笑哭】
用了快速幂,不过wa了一下,因为没考虑到int的最小值转化为正数后会爆掉。时间复杂度O(logn),空间复杂度O(1)
class Solution {
public:
double myPow(double x, int n) {
if (n == 0) return 1;
long long m = abs((long)n);
if (n < 0) {
x = 1 / x;
}
double ans = 1;
while (m > 0) {
if (m & 1) ans *= x;
x *= x;
m >>= 1;
}
return ans;
}
};
69. Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
本来还想用sqrt(x)做下比较,可能脑子进水了吧。。。时间复杂度O(logn),空间复杂度O(1)
class Solution {
public:
int mySqrt(int x) {
long long le = 0, ri = (long long)x + 1;
while (le < ri - 1) {
long long mid = (le + ri) >> 1;
if (mid * mid > x) ri = mid;
else le = mid;
}
return le;
}
};
367. Valid Perfect Square
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt
.
Example 1:
Input: 16 Returns: True
Example 2:
Input: 14 Returns: False
相当于69题换了个描述方法,本质还是实现sqrt(x)
时间复杂度O(logn),空间复杂度O(1)
class Solution {
public:
bool isPerfectSquare(int num) {
long long le = 0, ri = (long long)num + 1;
while (le < ri - 1) {
long long mid = (le + ri) >> 1;
if (mid * mid > num) ri = mid;
else le = mid;
}
if (le * le == (long long)num) return true;
return false;
}
};
633. Sum of Square Numbers
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a2 + b2 = c.
Example 1:
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3 Output: False
判断一个数能不能拆成两个平方和。
时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
bool judgeSquareSum(int c) {
int le = 0, ri = sqrt(c);
while (le <= ri) {
if (le * le + ri * ri == c) return true;
else if (le * le + ri * ri > c) ri--;
else le++;
}
return false;
}
};