【问题标题】:How can I get the offsets of all set bits in a bitarray?如何获取位数组中所有设置位的偏移量?
【发布时间】:2013-02-10 00:59:19
【问题描述】:

在 C、Ruby 或 PHP 中,如何获取位数组中所有设置位的偏移量。例如:

Bitarray:  1 0 0 1 0
Offset:    5 4 3 2 1
Yields 2 and 5.

10001 => {1,5}
11 => {1,2}
1001001 => {1,4,7}

最明显的解决方案是首先执行反向 Find first set 以了解长度,然后遍历位,保存偏移量/索引。然而,这似乎不是很聪明。像 FFSR 这样多次减法可能会更好。

【问题讨论】:

  • 您使用什么语言,到目前为止您尝试过什么?
  • 语言可以是 C 或 Ruby/PHP。
  • 那么,在 C 中,你的位数组表示是什么?
  • @GeorgeSkoptsov 语言不相关,因为这是一个算法问题。您可以用任何语言证明您的概念或复杂性。

标签: php c ruby offset bitarray


【解决方案1】:

我想出了这个。我已经使用二进制移位运算来确定是否存在二进制“1”或“0”。也许您可以使用此代码作为您的起点。

#include <stdio.h>

int main()
{
    int number;
    int counter = 1;

    printf("Please input the number to get the offsets: ");
    scanf("%d", &number);

    printf("The required positions of ones: ");
    while ((number != 0))
    {
        if ((number % 2) != 0)
        {
            number = number >> 1;
            printf("%d", counter);
        }
        else 
        {
            number = number >> 1;
        }   

        counter++;  
    }

    return 0;
}

这是一个扩展版本,也可以打印二进制表示:

#include <stdio.h>
#include <strings.h>

char* rev(char* str);

int main()
{
    int number, temp;
    int counter = 1;
    char str[32] = "";

    printf("Please input the number to get the offsets: ");
    scanf("%d", &number);
    temp = number;

    printf("Binary representation: ");
    while ((temp != 0))
    {
        if ((temp % 2) != 0)
        {
            temp = temp >> 1;
            strncat(str, "1", 1);
        }
        else 
        {
            temp = temp >> 1;
            strncat(str, "0", 1);
        }       
    }
    printf("%s", rev(str));

    printf("\nThe required positions of ones: ");
    while ((number != 0))
    {
        if ((number % 2) != 0)
        {
            number = number >> 1;
            printf("%d", counter);
        }
        else 
        {
            number = number >> 1;
        }   

        counter++;  
    }

    getch();
    getch();
    return 0;
}    

char* rev(char* str)
{
  int end= strlen(str) - 1;
  int start = 0;

  while( start<end )
  {
    str[start] ^= str[end];
    str[end] ^=   str[start];
    str[start]^= str[end];

    ++start;
    --end;
  }

  return str;
}

【讨论】:

  • 变速部分真的很聪明。
  • 这不是你要求的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
相关资源
最近更新 更多