1-line c++ code


  • 3
    Z

    Notice that n&-n = last 1 of n.

    class Solution {
    public:
        bool isPowerOfTwo(int n) {
            return n && n!=INT_MIN && n-(n&-n) == 0;
        }
    };

  • 1
    S
    class Solution {
    public:
        bool isPowerOfTwo(int n) {
            return 1 == __builtin_popcount(n) && n > 0;    
        }
    };

Log in to reply
 

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