leetcode :Binary Search:Valid Perfect Square(367)

来源:互联网 发布:php开源站群管理系统 编辑:程序博客网 时间:2024/06/07 07:34

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;        long x = num / 2, t = x * x;        while (t > num) {            x /= 2;            t = x * x;        }        for (int i = x; i <= 2 * x; ++i) {            if (i * i == num) return true;        }        return false;    }}; 
0 0
原创粉丝点击