0

你好,这是一个面试问题。

对于任何给定的数字,计算下一个能被 8 整除的数字。

即如果给定的数字是43,我们的算法应该产生48结果。如果数字已经被它整除,8它应该说Number already divisible by 8并产生下一个能被 8 整除的数字。

我建议他们将任何可被整除的数字的8最后三位为0(LSB+2,LSB+1,LSB)。但我无法给出确切的解决方案。

我说的是解决这个问题的正确方法还是我们可以寻求一些更聪明的解决方案?我需要通过位操作来做到这一点。

4

5 回答 5

8

你在正确的轨道上。

int next8(int n) {
    int bits = n & 7; // give us the distance to the previous 8
    if (bits == 0) printf("Number already divisible by 8");
    return n + (8-bits);
}

(注意:我讨厌它应该是纯打印的功能,但任务要求如此。对不起。)

于 2013-07-30T11:16:19.947 回答
8

next = current + 8 - (current % 8)

于 2013-07-30T11:17:33.513 回答
2

使用while循环很容易:

if number % 8 == 0
  already divisible by 8

while number % 8 != 0
  ++number

这是O(1),因为 8 是一个常数,但我们可以使用以下公式做得更好:

if number % 8 == 0
  already divisible by 8

number = number + 8 - number % 8
于 2013-07-30T11:15:44.030 回答
0

您的检查是正确的,要检查它,您可以对 7 执行按位与并确保它为 0 (X & 7 == 0)。要获得下一个数字 - 右移 3,加 1 并后移 ( ((X >> 3) + 1) << 3 )

于 2013-07-30T11:22:41.557 回答
0
void main()
{
   int n;
   printf("\n Enter the number:");
   scanf("%d",&n);
   if(n==8 && n%8==0)
   printf("%d it is already divisible by 8",n);
   else
   {
      printf("not divsible by 8 so nearest number is:");
      i=n/8;
      i++;
      n=i*8;
      printf("%d is next number divisible by 8",n);         
   }
}

你可以试试这个,这是解决方案之一

谢谢你。

于 2013-07-30T12:08:55.310 回答