leetcode 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
不用sqrt,判断这个数是不是完全平方数。
用二分来实现sqrt进行判断。
class Solution {
public:
bool isPerfectSquare(int num) {
int l = 1;
int r = num;
if (num == 1) return true;
int mid;
while (l < r) {
mid = l + (r - l + 1) / 2;
if (mid > num / mid) {
r = mid - 1;
} else if (mid < num / mid){
l = mid;
} else {
if (mid * mid == num) return true;
else return false;
}
//cout << l << " " << r << endl;
}
//cout << mid << endl;
return false;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: