AC solution in Java with BitSet


  • 1
    L
    public class Solution {
        public int countPrimes(int n) {
            if (n <= 2) return 0;
            BitSet compounds = new BitSet(n);
            int count = 0;
            for (int i = 2; i < n; i++) {
                if (compounds.get(i) == false) {
                    count++;
                    for (int j = i + i; j < n; j += i) compounds.set(j);
                }
            }
            return count;
        }
    }

  • 0
    S

    Any explanation behind your code is greatly appreciated! :)


Log in to reply
 

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