leetcode :Binary Search: Valid Perfect Square(367)

原创 2016年08月30日 14:43:06

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;
    }
}; 
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode - 367. Valid Perfect Square

一开始的想法是从1到n / 2 + 1逐个遍历,看i * i == n?但是这样写应该是无法通过LeetCode测试的,因为一般只要涉及到i * i的问题,LeetCode都会给出一个非常大的数字,让...

<LeetCode OJ> 69 / 367 Sqrt(x) / Valid Perfect Square

69. Sqrt(x) My Submissions Question Total Accepted: 79525 Total Submissions: 325488 Difficulty: ...

Binary search (2) -- Heaters, Valid Perfect Square

Heaters,Valid Perfect Square
  • dwt0317
  • dwt0317
  • 2017年01月16日 21:48
  • 203

14. Longest Common Prefix\441. Arranging Coins\367. Valid Perfect Square

Longest Common Prefix 题目描述 代码实现 Arranging Coins 题目描述 代码实现 Add Strings 题目描述 代码实现 Valid Perfect Square...

[LeetCode]422. Valid Word Square

Given a sequence of words, check whether it forms a valid word square. A sequence of words forms ...

第十四周:( LeetCode593) Valid Square(c++)

给出四个点的坐标,判断这四个点能否构成正方形。

LeetCode: Valid Word Square

这是 LeetCode 上的一题目:Valid Word Square

【LeetCode】99. Recover Binary Search Tree 分析、解法、注释、中序遍历、递归

99. Recover Binary Search Tree Total Accepted: 50739 Total Submissions: 192395 Difficulty: Hard...

《leetCode》:Binary Search Tree Iterator

Binary Search Tree Iterator题目如下:Implement an iterator over a binary search tree (BST). Your iterator...

leetcode98---Validate Binary Search Tree

问题描述:Given a binary tree, determine if it is a valid binary search tree (BST).Assume a BST is define...
  • will130
  • will130
  • 2015年12月26日 13:15
  • 212
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode :Binary Search: Valid Perfect Square(367)
举报原因:
原因补充:

(最多只允许输入30个字)