Skip to content

Commit 3579de6

Browse files
refactor 762
1 parent e386b18 commit 3579de6

File tree

1 file changed

+28
-65
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+28
-65
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,37 @@
11
package com.fishercoder.solutions;
22

3-
/**
4-
* 762. Prime Number of Set Bits in Binary Representation
5-
*
6-
* Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
7-
* (Recall that the number of set bits an integer has is the number of 1s present when written in binary.
8-
* For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)
9-
10-
Example 1:
11-
12-
Input: L = 6, R = 10
13-
Output: 4
14-
15-
Explanation:
16-
6 -> 110 (2 set bits, 2 is prime)
17-
7 -> 111 (3 set bits, 3 is prime)
18-
9 -> 1001 (2 set bits , 2 is prime)
19-
10->1010 (2 set bits , 2 is prime)
20-
21-
Example 2:
22-
23-
Input: L = 10, R = 15
24-
Output: 5
25-
26-
Explanation:
27-
10 -> 1010 (2 set bits, 2 is prime)
28-
11 -> 1011 (3 set bits, 3 is prime)
29-
12 -> 1100 (2 set bits, 2 is prime)
30-
13 -> 1101 (3 set bits, 3 is prime)
31-
14 -> 1110 (3 set bits, 3 is prime)
32-
15 -> 1111 (4 set bits, 4 is not prime)
33-
34-
Note:
35-
36-
L, R will be integers L <= R in the range [1, 10^6].
37-
R - L will be at most 10000.
38-
*/
39-
403
public class _762 {
41-
public static class Solution1 {
42-
public int countPrimeSetBits(int L, int R) {
43-
int count = 0;
44-
for (int i = L; i <= R; i++) {
45-
if (hasPrimeNumberSetBits(i)) {
46-
count++;
4+
public static class Solution1 {
5+
public int countPrimeSetBits(int L, int R) {
6+
int count = 0;
7+
for (int i = L; i <= R; i++) {
8+
if (hasPrimeNumberSetBits(i)) {
9+
count++;
10+
}
11+
}
12+
return count;
4713
}
48-
}
49-
return count;
50-
}
5114

52-
private boolean hasPrimeNumberSetBits(int num) {
53-
int k = getSetBits(num);
54-
if (k <= 1) {
55-
return false;
56-
}
57-
for (int i = 2; i * i <= k; i++) {
58-
if (k % i == 0) {
59-
return false;
15+
private boolean hasPrimeNumberSetBits(int num) {
16+
int k = getSetBits(num);
17+
if (k <= 1) {
18+
return false;
19+
}
20+
for (int i = 2; i * i <= k; i++) {
21+
if (k % i == 0) {
22+
return false;
23+
}
24+
}
25+
return true;
6026
}
61-
}
62-
return true;
63-
}
6427

65-
private int getSetBits(int n) {
66-
int bits = 0;
67-
while (n != 0) {
68-
bits++;
69-
n &= (n - 1);
70-
}
71-
return bits;
28+
private int getSetBits(int n) {
29+
int bits = 0;
30+
while (n != 0) {
31+
bits++;
32+
n &= (n - 1);
33+
}
34+
return bits;
35+
}
7236
}
73-
}
7437
}

0 commit comments

Comments
 (0)