2015年11月3日星期二

Leetcode 231 Power of Two

Given an integer, write a function to determine if it is a power of two.
Solution 1: count the binary bits, should be only 1.
 public class Solution {  
   public boolean isPowerOfTwo(int n) {  
     if (n<0) return false;  
     int count=0;  
     for (int i=0; i<32; i++)   
       if ((n>>i&1)==1) count++;  
     return count==1;  
   }  
 }  

没有评论:

发表评论