---
# System prepended metadata

title: Valid Perfect Square練習
tags: [leetcode]

---

## Valid Perfect Square練習
這題其實跟[Sqrt(x)](https://hackmd.io/@er0M3STVTRW2uR3r_2A16g/HJ1Psz8D-l)的概念是一樣的，甚至還更單純一點，兩邊搭配著做可能會比較好理解觀念。

## 解法
```php=
class Solution {

    /**
     * @param Integer $num
     * @return Boolean
     */
    function isPerfectSquare($num) {
        $left=1;
        $right=$num;
        while($left<=$right){
            if($num==1){
                return true;
            }
            $mid=intdiv(($left+$right),2);
            $square=$mid*$mid;
            if($square==$num){
                return true;
            }

            if($square>$num){
                $right=$mid-1;
            }elseif($square<$num){
                $left=$mid+1;
            }

        }

        return false;
    }
}
```