leetcode 69. Sqrt(x) 367. Valid Perfect Square
2017-11-20 10:24
597 查看
69. Sqrt(x)
Implement
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Example 2:
二分法:二分答案。
使用二分法标准格式。
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
Example 1:
Example 2:
和上面的题做法一模一样。二分法。
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) ;
}
};
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) ;
}
};
相关文章推荐
- 【Leetcode】69.Sqrt(x)
- LeetCode||69. Sqrt(x)
- The Solution to LeetCode 69 Sqrt(x)
- Leetcode 69. Sqrt(x)
- LeetCode --- 69. Sqrt(x)
- LeetCode 69: Sqrt(x)
- [Leetcode]69.Sqrt(x)
- [leetcode] 【分治法】 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- LeetCode【69】 Sqrt(x)
- [leetcode:python]69.Sqrt(x)
- leetCode 69.Sqrt(x) (平方根) 解题思路和方法
- Leetcode 69 Sqrt(x) 求x开根号的整数部分
- 69. Sqrt(x) LeetCode
- 【LeetCode 69】Sqrt(x) (Python)
- Leetcode刷题记—— 69. Sqrt(x)(求整数x的平方根)
- 【Leetcode】69. Sqrt(x) 【溢出?如何防止?】
- LeetCode-69. Sqrt(x)
- LeetCode 69 — Sqrt(x)(C++ Java Python)
- 【leetcode】69. Sqrt(x)(Python & C++)