762. Prime Number of Set Bits in Binary Representation

762. Prime Number of Set Bits in Binary Representation

class Solution {
   	boolean isPrime(int n) {
        if( n ==1 ) return false;
		for (int i = 2; i < n; i++) {
			if (n % i == 0)
				return false;
		}
		return true;
	}

	public int countPrimeSetBits(int L, int R) {
		int count = 0;
		for (int i = L; i <= R; i++) {
			String binary = Integer.toBinaryString(i);
			int setBits = 0;
			for (int j = 0; j < binary.length(); j++)
				if (binary.charAt(j) == '1')
					setBits++;
			if (isPrime(setBits))
				count++;
		}
		return count;
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s