Valid Perfect Square LeetCode Solution

Problem – Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Follow up: Do not use any built-in library function such as sqrt.

Example 1:

Input: num = 16
Output: true

Example 2:

Input: num = 14
Output: false

Constraints:

  • 1 <= num <= 2^31 - 1

Valid Perfect Square LeetCode Solution in Python

    def BitwiseTrick(self, num):
       root = 0
       bit = 1 << 15
       
       while bit > 0 :
           root |= bit
           if root > num // root:    
               root ^= bit                
           bit >>= 1        
       return root * root == num

Valid Perfect Square LeetCode Solution in C++

class Solution {
public:
    bool isPerfectSquare(int num) {
        int a=1;
        
        while(num>0){
            num-=a;
            a+=2;
        }
        return(num==0);
    }
};

Valid Perfect Square LeetCode Solution in Java

class Solution {
    public boolean isPerfectSquare(int num) {
        long left = 1, right = num;
        while (left <= right) {
            long mid = (left + right) / 2;
            if (mid * mid == num) return true; // check if mid is perfect square
            if (mid * mid < num) { // mid is small -> go right to increase mid
                left = mid + 1;
            } else {
                right = mid - 1; // mid is large -> to left to decrease mid
            }
        }
        return false;
    }
}
Valid Perfect Square LeetCode Solution Review:

In our experience, we suggest you solve this Valid Perfect Square LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Valid Perfect Square LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Valid Perfect Square LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.