相关疑难解决方法(0)

将整数更改为二进制数字字符串

我目前正在使用C++模拟MIPS处理器,用于comp体系结构类,并且在从十进制数转换为二进制数(双向带符号数)方面存在一些问题.一切正常,直到最后一点,因为我的当前算法在1 << = 31时落入int的界限区域.只需要朝着正确的方向轻推即可启动并运行.谢谢!

//Assume 32 bit decimal number
string DecimalToBinaryString(int a)
{
    string binary = "";
    int mask = 1;
    for(int i = 0; i < 31; i++)
    {
        if((mask&a) >= 1)
            binary = "1"+binary;
        else
            binary = "0"+binary;
        mask<<=1;
    }
    cout<<binary<<endl;
    return binary;
}
Run Code Online (Sandbox Code Playgroud)

我还包括我的其他算法的完整性.我为缺乏评论而道歉,但这是相当直接的.

int BinaryStringToDecimal(string a)
{
    int num = 0;
    bool neg = false;
    if(a.at(0) == '1')
    {
        neg = true;
        for(int x = a.length()-1; x >= 0; x--)
        {
            if(a.at(x) == '1')
                a.at(x) = …
Run Code Online (Sandbox Code Playgroud)

c++ algorithm binary

23
推荐指数
2
解决办法
7万
查看次数

计数十进制数的二进制格式的1

我试图找出大十进制数的二进制形式的1的数量(十进制数可以大到1000000).

我尝试了这段代码:

while(sum>0)  
{  
    if(sum%2 != 0)  
    {  
        c++;   // counting number of ones  
    }  
    sum=sum/2;  
}  
Run Code Online (Sandbox Code Playgroud)

我想要一个更快的算法,因为大十进制输入需要很长时间.请建议我一个有效的算法.

c++ binary decimal

5
推荐指数
3
解决办法
2万
查看次数

如何在O(1)时间内找到二进制数的1?

我知道之前有人问过,但我正在看这里列出的特定解决方案:

int BitCount(unsigned int u)
{
     unsigned int uCount;

     uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
     return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}
Run Code Online (Sandbox Code Playgroud)

它是如何工作的?

这里有什么警告吗?

理论上可以在恒定的时间内找到答案吗?我的意思是,我们实际上不必迭代这些位来计算?

c algorithm bit-manipulation

4
推荐指数
3
解决办法
4285
查看次数

numpy矢量化方法来计算整数数组中的非零位

我有一个整数数组:

[int1, int2, ..., intn]
Run Code Online (Sandbox Code Playgroud)

我想计算这些整数的二进制表示中有多少非零位。

例如:

bin(123) -> 0b1111011, there are 6 non-zero bits
Run Code Online (Sandbox Code Playgroud)

当然,我可以遍历整数、用途bin()count('1')函数的列表,但我正在寻找矢量化的方法来做到这一点。

python arrays numpy vectorization

3
推荐指数
2
解决办法
170
查看次数

以 O(n) 和 O(log n) 的二进制表示计数 1,其中 n 是位数

我有两个任务 - 在 O(n) 和 O(log n) 中以二进制表示计数 1。由于第一部分很简单,我不知道如何在 O(log n) 中计算它们,因为它没有排序或任何东西。这甚至可能吗?到目前为止我的代码:

public class CountOnes {
  public static void main(String[] args)
  {
    System.out.println("Program to count ones");
    countOnesInLinearTime("110");
    countOnesInlogarithmicTime("110");
  }

  private static void countOnesInlogarithmicTime(String binaryRepresentationOfLong) {
    //TODO
  }

  private static void countOnesInLinearTime(String binaryRepresentationOfLong) {
    int numberOfOnes = 0;
    for(int i = 0; i < binaryRepresentationOfLong.length(); i++)
    {
      if(binaryRepresentationOfLong.charAt(i) == '1')
      {
        numberOfOnes++;
      }
    }
    System.out.println(numberOfOnes);
  }
}
Run Code Online (Sandbox Code Playgroud)

我发现:以二进制表示计算 1 的数量,但略有不同。

java algorithm binary time-complexity

2
推荐指数
1
解决办法
1687
查看次数