检查整数是否为0的最佳方法

NAM*_*AMO -2 language-agnostic optimization

检查整数中是否为0(零)的最佳方法是什么

例如:

505 -> True
555 -> False
44444032 -> True
0000 -> True
Run Code Online (Sandbox Code Playgroud)

我试过这个

public bool has0(int no)
{
    if(no==0)return true;
    while(no!=0)
    {
        if(no%10==0)return true;
        no=no/10;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,但考虑到我需要在大数字上专门调用此方法10亿次,因此需要特别花费大量时间

for(int i=0;i<1000000000;i++)has0(i);
Run Code Online (Sandbox Code Playgroud)

那么,什么将是检查的最佳方式,如果在一些存在通过使用一些位级运营商如0 |,&,^或任何其他方式.

谢谢..

fra*_*ji1 8

Modulo是一种昂贵的整数运算(类似于整数除法).您可以通过查看数字是否均匀来消除测试中一半可能的答案.没有奇数的模10等于零.

if(((no&0x1)== 0x00)&&((no%10)== 0))return true;

你会在偶数上付出更多,但在奇数上却少得多.因此,如果它是所有偶数,这将无济于事(它实际上会受到伤害),但如果它是50/50甚至20/80(20%奇数),你可能仍然会领先.

此外,整数乘法更便宜,因此您可以先进行除法并计算模10.

while (no)
{
  if (no & 0x1))  // odd?
    no /= 10;
  else  // even
  {
    int nNext = no / 10;  // just do integer divide, and calculate modulo in next line
    if ((no - (10 * nNext)) == 0)  // replaces "more expensive" modulo operation with integer multiply and subtraction
      return true;
    no = nNext;
  }
}
Run Code Online (Sandbox Code Playgroud)