zoukankan      html  css  js  c++  java
  • 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

     

    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)

  • 相关阅读:
    Kotlin基本语法笔记3之定义类、继承及创建实例
    Kotlin基本语法笔记2之类型检测及自动类型转换、循环
    Kotlin基本语法笔记之函数、变量的定义及null检测
    C++笔记之外部类访问内部类的私有成员
    正则表达式之不区分大小写的匹配
    springMVC之helloworld
    数组学习
    反射reflect
    JSP学习
    自己做的菜
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6821265.html
Copyright © 2011-2022 走看看