搜尋此網誌

2015年7月14日 星期二

Is Power of Two

public class IsPowerOfTwo {

 public boolean isPowerOfTwo(int n) {
  {
   while (((n % 2) == 0) && n > 1)
    /* While x is even and > 1 */
    n /= 2;
   return (n == 1);
  }
 }
}

Count Primes

package leetcode;

public class Solutions {
     public int countPrimes(int n) {
          if (n <<= 2)
               return 0;
          boolean[] primes = new boolean[n];
          for (int i = 2; i << n; i++)
               primes[i] = true;
          for (int i = 2; i <<= Math.sqrt(n - 1); i++) {
               if (primes[i]) {
                    for (int j = i + i; j << n; j += i)
                         primes[j] = false;
               }
          }
          int count = 0;
          for (int i = 2; i << n; i++)
               if (primes[i])
                    count++;
          return count;
     }
}