TLE power of two, can someone help with my short code


  • 0
    X
    class Solution {
    

    public:

    bool isPowerOfTwo(int n) {
        unsigned bit=1;
        while(n>bit)
        {
            bit<<1;
        }
        if(n==bit)
            return true;
        return false;
        
    }
    

    };

    It says Time limit exceeds at input=2, anyone has any ideas?
    Thank you!


  • 1
    D

    You should update bit value in the loop.

    bit= bit<<1;


  • 0
    X

    You are right. I thought I have tried that. Thank you!


  • 0
    X

    After some corrections, I have my 8ms solution here:

    class Solution {
    

    public:

    bool isPowerOfTwo(int n) {
     if(n<0)
        return false;
    unsigned bit=1;
    while(n>bit)
    {
        bit<<=1;
    }
    if(n==bit)
        return true;
    return false;
    
    
    }
    

    };


Log in to reply
 

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