Java Solution: one line


  • 15
    B
    public class Solution {
        public boolean isPowerOfTwo(int n) {
        /**
         * There is two accepted answers,the former is better.
         */
        return n <= 0 ? false : (n & (n - 1)) == 0;
        // return n <= 0 ? false : n == Math.pow(2, (int) (Math.log(n) / Math.log(2)));
        }
    }

  • 0
    M

    your answer is equivalent to:
    return n > 0 && (n & (n - 1)) == 0;


Log in to reply
 

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