leetcode_Valid Perfect Square
2016-07-05 16:58
351 查看
[题目]
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
【解法】
二分查找,从1 – num/2,因为除了1和4,一个数的开平方肯定小于这个数的一半,过程中注意溢出,因为两个比较大的int型相乘,可能溢出,因此程序中使用了long long类型。
【代码】
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
【解法】
二分查找,从1 – num/2,因为除了1和4,一个数的开平方肯定小于这个数的一半,过程中注意溢出,因为两个比较大的int型相乘,可能溢出,因此程序中使用了long long类型。
【代码】
#include<iostream> #include<math.h> using namespace std; bool isPerfectSquare(int num1) { long long num = (long long) num1; if(num == 0 || num == 1 || num == 4) return true; int temp = num/2+1; int left = 1; int right = temp; while(left <= right) { //打印过程 //cout<<"("<<left<<","<<right<<")"<<endl; //long long防止溢出 long long mid = left + (right - left) / 2; if(mid * mid == num) return true; else if(mid * mid < num) left = mid + 1; else right = mid - 1; } return false; } int main(void) { for(int i = 1;i <= 1024;i++) { if(isPerfectSquare(i)) cout<<isPerfectSquare(i)<<endl; } system("pause"); return 0; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解