二进制间隙(Binary Gap)算法

定义:

binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

二进制间隙 - 给定一个正整数N, 它对应的二进制数字中在任意两个端被1包围的连续0的最大序列.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

举个列子:

9 的二进制是1001, 它的二进制间隙的最大序列长度就是2

529 的二进制表示是1000010001 , 这个数字包含两个连续为0的序列, 一个是100001,一个是10001, 所以取最大连续为0的长度就是4.

20 的二进制表示是10100, 它的连续为0的最大序列长度就是1.

15 的二进制表示是1111, 并不存在二进制间隙, 所以连续为0的最大序列长度为0.

32 的二进制是100000,也不存在二进制间隙, 所以连续为0的最大序列长度为0

算法1思想

1. 将十进制转换为二进制

2. 遍历二进制每一位,获取所有值为1的index集合

3. 因为索引是连续的,遍历每个索引的值。计算连续0的个数。

4. 取连续为0个数最多的值

下面是实现代码: 

int N =9;
List<int> binaryNumber = new List<int>();
//1. Convert the number to binary and push it to binaryNumber list
while(N>=1){
    int result = N%2;
    binaryNumber.Add(result);
    N = N/2;
}
//Reverse the list to make sure the binary number is correct. Because the binary should generate from end to begining
binaryNumber.Reverse();
foreach(var item in binaryNumber){
    Console.WriteLine(item);
}
//Set two f;ags to identify the 1 and 0
int flag = 1;
int flagOfZero = 0;
//Get all the indexes of 1 in the binary numbers.
List<int> indexes = new List<int>();
for(int i = 0; i < binaryNumber.Count; i++){
    if(flag == binaryNumber[i]){
         indexes.Add(i);
    }
}
int count = 0;
//iterate the index arry to get the max sequences of the binary number
for(var i = 0; i < indexes.Count - 1; i++){
    int currentCount = 0;
    var index = indexes[i];
    for(int j = index; j < indexes[i+1]; j++){
        if(binaryNumber[j] == 0){
            currentCount++;
        }
    }

    if(count < currentCount)
        count = currentCount;
}

Console.WriteLine(count);

算法2思想

1. 将十进制转换为二进制

2. 遍历二进制每一位,获取所有值为1的index集合

3. 因为索引是连续的,后面的索引和前面的索引的差值减1就是 最大的二进制间隙

4. 返回最大值

下面上代码

def solution(N):
    number = N
    bitnumber = []
    while number > 0:
        bitnumber.append(number % 2)
        number = number // 2
    bn = bitnumber[::-1]
    bn_lenth = len(bn)
    bn_index = []
    for i in range(bn_lenth):
        if bn[i] == 1:
            bn_index.append(i)
        else:
            pass
    if len(bn_index) < 2:
        return 0
    max = 0
    for i in range(len(bn_index)-1):
        dis=bn_index[i+1]-bn_index[i]-1
        if dis>max:
            max=dis
    return max
"""
Get the binary gap
:parameter N: the specific number
"""
def solution1(N):
    """
    1. Get the binary number
    2. Get the index collection which the value is 1 in the binary
    3. Calculate the max gap between the current index and the one in front
    4. Return the max gap
    """
    number = N    
    bit_number = {}
    i = 0
    while number > 0:
        bit_number[i] = number % 2
        number = number // 2
        i+=1
    pre_result = {}
    pre_index = 0;
    for index in bit_number:
        if bit_number[index] == 1:
            pre_result[pre_index] = index
            pre_index+=1
    max = 0
    for f_index in range(len(pre_result) - 1):
        result = pre_result[f_index + 1] - pre_result[f_index] - 1
        if max < result:
           max = result
    return max

其中十进制转二进制使用除2取余方法, 从后向前组装成二进制数字

 

posted @ 2022-09-13 16:07  竹林溪风  阅读(434)  评论(0编辑  收藏  举报