码迷,mamicode.com
首页 > 其他好文 > 详细

367. Valid Perfect Square

时间:2017-05-07 17:44:02      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:class   strong   function   ica   span   begin   wan   which   use   

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

 

Solution 1: use BST,O(logn)

 1 class Solution {
 2 public:
 3     bool isPerfectSquare(int num) {
 4         if (num==1) return true;
 5         int begin=0,end=num;
 6         while (begin<end-1){
 7             long long mid=(begin+end)/2;
 8             if (mid*mid==num) return true;
 9             if (mid*mid<num) begin=mid;
10             if (mid*mid>num) end=mid;
11         } 
12         return false;
13     }
14 };

Solution 2: Newton‘s method,  http://blog.csdn.net/wangxiaojun911/article/details/18203333

1 class Solution {
2 public:
3     bool isPerfectSquare(int num) {
4         long long x=num;
5         while(x*x>num) x=(x+num/x)/2;
6         return x*x==num;
7     }
8 };

Soulution 3:  q_math.c special method, O(1)

367. Valid Perfect Square

标签:class   strong   function   ica   span   begin   wan   which   use   

原文地址:http://www.cnblogs.com/anghostcici/p/6821265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!