解决此问题的一种快速方法是扫描数字的位,直到找到两个连续的1s。发生这种情况时,您想修复它。换句话说,您想要制作一个比当前数字略大的数字。究竟要大多少?
考虑11 两侧的位:
...11...
我们会说11... 是当前号码的后缀。想象一下,我们一直在后缀上加 1,直到 11 消失。那什么时候会发生?好吧,11 不会变成10 或01,因为这会使它变小。我们只是在增加数量。
11 只会在后缀变为00... 时消失。最小的此类后缀由全零组成。因此,当我们遇到11 时,我们可以立即将其清零,并将其后的所有位清零。然后我们将1添加到后缀左侧的位中。
例如,考虑这个数字中最右边的11:
1000101011000100
^^
suffix: 11000100
prefix: 10001010
我们将后缀归零并在前缀上加一:
suffix: 00000000
prefix: 10001011
result: 1000101100000000
现在我们继续向左搜索,寻找下一个11。
以下函数右移以将后缀归零,将前缀加一,然后左移以将前缀恢复到其位置。
int next(int x) { /* Look for a number bigger than x. */
x += 1;
int mask = 3, /* Use the mask to look for 11. */
pos = 2; /* Track our location in the bits. */
while (mask <= x) {
if ((mask & x) == mask) { /* If we find 11, shift right to */
x >>= pos; /* zero it out. */
x += 1; /* Add 1, shift back to the left, */
x <<= pos; /* and continue the search. */
}
mask <<= 1; /* Advance the mask (could advance */
pos += 1; /* another bit in the above case). */
}
return x;
}
这种方法对输入的每一位执行恒定数量的操作,使其比蛮力方法快很多。形式上,运行时间与输入大小成对数。
下面是一个完整的程序,它在命令行中获取x 的值。
#include <stdlib.h>
#include <stdio.h>
void display(int x) {
int p = 1;
while (p < x) {
p <<= 1;
}
while (p != 0) {
printf("%d", (x & p) ? 1 : 0);
p >>= 1;
}
}
int next(int x) { /* Look for a number bigger than x. */
x += 1;
int mask = 3, /* Use the mask to look for 11. */
pos = 2; /* Track our location in the bits. */
while (mask <= x) {
if ((mask & x) == mask) { /* If we find 11, shift right to */
x >>= pos; /* zero it out. */
x += 1; /* Add 1, shift back to the left, */
x <<= pos; /* and continue the search. */
}
mask <<= 1; /* Advance the mask (could advance */
pos += 1; /* another bit in the above case). */
}
return x;
}
int main(int arg_num, char** args) {
int x, y;
if (arg_num != 2) {
printf("must specify a number\n");
return 0;
}
x = atoi(args[1]);
y = next(x);
printf("%d -> %d\n", x, y);
display(x);
printf(" -> ");
display(y);
printf("\n");
return 0;
}