您的位置:首页 > Web前端

leetcode 69. Sqrt(x) 367. Valid Perfect Square

2017-11-20 10:24 597 查看
69. Sqrt(x)

Implement 
int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.

Example 1:
Input: 4
Output: 2


Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.


二分法:二分答案。
使用二分法标准格式。

class Solution {
public:
int mySqrt(int target)
{
int start = 0;
int end = min(target, 46340);
while (start + 1 < end)
{
int mid = (end - start) /2 + start;
if (mid * mid == target)
return mid;
else if (mid * mid > target)
end = mid;
else
start = mid;
}
//double check
if (end * end <= target)
return end;
else
return start;
}
};


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

和上面的题做法一模一样。二分法。

class Solution {
public:
bool isPerfectSquare(int num)
{
if (num <= 1) return true;
int start = 1, end = min(num, 46340);
while (start + 1 < end)
{
int mid = (end - start) / 2 + start;
if (mid * mid == num) return true;
else if (mid * mid < num) start = mid;
else end = mid;
}
//double check
return (start * start == num || end * end == num) ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: