C++ / Python 0ms simple solution


  • 0
    A

    C++ version:

    class Solution {
    public:
        bool isPerfectSquare(int num) {
            int lsd = num % 10;
            if (lsd == 2 || lsd == 3 || lsd == 7 || lsd == 8) return false;
            double x_new = num / 2.0, x_old = 0;
            while (abs(x_new - x_old) > 1e-4){
                x_old = x_new;
                x_new = num / (2.0 * x_old) + x_old / 2.0;
            }
            x_new = static_cast<int>(x_new);
            return num == x_new * x_new;
        }
    };
    

    Python version:

    class Solution(object):
        def isPerfectSquare(self, num):
            """
            :type num: int
            :rtype: bool
            """
            if num % 10 not in [0,1,4,5,6,9]:
                return False
            x_new, x_old = num / 2.0, 0
            while abs(x_new - x_old) >= 1e-4:
                x_old = x_new
                x_new = num / (2.0 * x_old) + x_old / 2.0
            return num == int(x_new) ** 2

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.