|
3 | 3 | import java.util.ArrayList;
|
4 | 4 | import java.util.List;
|
5 | 5 |
|
6 |
| -/** |
7 |
| - * 868. Binary Gap |
8 |
| - * |
9 |
| - * Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N. |
10 |
| - * |
11 |
| - * If there aren't two consecutive 1's, return 0. |
12 |
| - * |
13 |
| - * Example 1: |
14 |
| - * Input: 22 |
15 |
| - * Output: 2 |
16 |
| - * Explanation: |
17 |
| - * 22 in binary is 0b10110. |
18 |
| - * In the binary representation of 22, there are three ones, and two consecutive pairs of 1's. |
19 |
| - * The first consecutive pair of 1's have distance 2. |
20 |
| - * The second consecutive pair of 1's have distance 1. |
21 |
| - * The answer is the largest of these two distances, which is 2. |
22 |
| - * |
23 |
| - * Example 2: |
24 |
| - * Input: 5 |
25 |
| - * Output: 2 |
26 |
| - * Explanation: |
27 |
| - * 5 in binary is 0b101. |
28 |
| - * |
29 |
| - * Example 3: |
30 |
| - * Input: 6 |
31 |
| - * Output: 1 |
32 |
| - * Explanation: |
33 |
| - * 6 in binary is 0b110. |
34 |
| - * |
35 |
| - * Example 4: |
36 |
| - * Input: 8 |
37 |
| - * Output: 0 |
38 |
| - * Explanation: |
39 |
| - * 8 in binary is 0b1000. |
40 |
| - * There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0. |
41 |
| - * |
42 |
| - * Note: |
43 |
| - * 1 <= N <= 10^9 |
44 |
| - */ |
45 | 6 | public class _868 {
|
46 |
| - public static class Solution1 { |
47 |
| - public int binaryGap(int N) { |
48 |
| - String bin = Integer.toBinaryString(N); |
49 |
| - List<Integer> oneIndexes = new ArrayList<>(); |
50 |
| - for (int i = 0; i < bin.length(); i++) { |
51 |
| - if (bin.charAt(i) == '1') { |
52 |
| - oneIndexes.add(i); |
| 7 | + public static class Solution1 { |
| 8 | + public int binaryGap(int N) { |
| 9 | + String bin = Integer.toBinaryString(N); |
| 10 | + List<Integer> oneIndexes = new ArrayList<>(); |
| 11 | + for (int i = 0; i < bin.length(); i++) { |
| 12 | + if (bin.charAt(i) == '1') { |
| 13 | + oneIndexes.add(i); |
| 14 | + } |
| 15 | + } |
| 16 | + int maxGap = 0; |
| 17 | + for (int i = 0; i < oneIndexes.size() - 1; i++) { |
| 18 | + maxGap = Math.max(oneIndexes.get(i + 1) - oneIndexes.get(i), maxGap); |
| 19 | + } |
| 20 | + return maxGap; |
53 | 21 | }
|
54 |
| - } |
55 |
| - int maxGap = 0; |
56 |
| - for (int i = 0; i < oneIndexes.size() - 1; i++) { |
57 |
| - maxGap = Math.max(oneIndexes.get(i + 1) - oneIndexes.get(i), maxGap); |
58 |
| - } |
59 |
| - return maxGap; |
60 | 22 | }
|
61 |
| - } |
62 | 23 | }
|
0 commit comments