LeetCode-Binary Gap

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82892380

Description:
Given a positive integer N, find and return the longest distance between two consecutive 1’s in the binary representation of N.

If there aren’t two consecutive 1’s, return 0.

Example 1:

Input: 22
Output: 2
Explanation: 
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
The first consecutive pair of 1's have distance 2.
The second consecutive pair of 1's have distance 1.
The answer is the largest of these two distances, which is 2.

Example 2:

Input: 5
Output: 2
Explanation: 
5 in binary is 0b101.

Example 3:

Input: 6
Output: 1
Explanation: 
6 in binary is 0b110.

Example 4:

Input: 8
Output: 0
Explanation: 
8 in binary is 0b1000.
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.

Note:

  • 1 <= N <= 10^9

题意:将一个正整数表示为二进制形式,计算两个连续的1的最远距离;

解法:连续的1可以只包含一个1,也可以包含多个1;并且计算的两个连续的1时,这两个连续的1是相邻的;

  • 例如:对于0b11101101来说,并不是只有3个连续的1,第一个111是一个连续的1,但是第一个111中的11和1也是连续的1

首先,我们需要做的是将整数转换为二进制,可以使用移位操作,每次将最后一位移出;接下来我们可以用一个变量preOneIndex表示前一个1出现的位置,这样每当出现一个新的1时,我们计算距离,保存最大的距离,同时更新preOneIndex为当前1的位置;

Java
class Solution {
    public int binaryGap(int N) {
        List<Integer> binary = new ArrayList<>();
        int dis = 0;
        int preOneIndex = -1;
        while (N > 0) {
            binary.add(N & 0x01);
            N >>= 1;
        }
        for (int i = 0; i < binary.size();) {
            while (preOneIndex == -1 && binary.get(i) == 0) i++;
            preOneIndex = preOneIndex == -1 ? i++ : preOneIndex;
            while (i < binary.size() && binary.get(i) == 0) i++;
            if (i >= binary.size()) break;
            dis = Math.max(dis, i - preOneIndex);
            preOneIndex = i++;
        }
        return dis;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82892380
GAP
GAP