代码之家  ›  专栏  ›  技术社区  ›  DecPK

用大n检验正整数n的幂为2的错误

  •  1
  • DecPK  · 技术社区  · 8 年前

    我有这个程序来检查一个no是否是2的幂,但是如果 no = 1099511627776 以下内容:

    int not; // no of testcase
    unsigned long long int no; // input number
    int arr[100];
    scanf ("%d", &not);
    
    for ( int i = 0; i < not; i++ )
    {
        scanf ("%llu", &no);
        if ( no & !(no & (no - 1))) // check wheather no is power of 2 or not excludig 0
            arr[ i ] = 1;
        else
            arr[ i ] = 0;
    }
    for ( int i = 0; i < not; i++ )
    {
        if ( arr[ i ] == 1 )
            printf ("YES\n");
        else
            printf ("NO\n");
    }
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   Sergey Kalinichenko    8 年前

    你得到一个错误,因为你的比较 no 对于使用 & 接线员。

    当一个值被自己使用时,您可以避开这个问题,但是 是2的幂 0 在最低有效位, no & [some-logical-expression] 产量为零。

    您可以通过三种方式解决此问题:

    • 使用 && 代替 & ,即 no && !(no & (no - 1))
    • 添加 !! 在前面 ,即 !!no & !(no & (no - 1))
    • 将显式比较添加到零,即。 no!=0 & !(no & (no - 1)) 是的。

    我非常喜欢第一种方法。

    Demo.

        2
  •  0
  •   Eric Postpischil    8 年前

    & 是按位和。您需要逻辑和: no && !(no & (no - 1)) 是的。

        3
  •  0
  •   Achal    8 年前

    以下是我对你提到的代码的一些观察。

    首先 ,如果用户给定 not 价值大于 100 是吗?它引起 未定义的行为 如果 not>100 正如你所宣称的 arr 作为尺寸 100个 是的。避免这种情况的方法是先扫描 然后创建等于 大小。例如

    int not = 0; // no of testcase
    scanf ("%d", &not);
    int arr[not]; /* create array equal to not size.. */
    

    或者动态创建数组

    int not = 0; // no of testcase
    scanf ("%d", &not);
    int *arr = malloc(not * sizeof(*arr)); /* create dynamic array equal to not size.. */
    

    其次 ,检查给定的数字是否为2的幂 !(no & (no - 1)) 是正确的,但要排除 zero 即如果给定输入 no 0 那你不应该检查 啊!(1号) 这个。为此,逻辑和 && 接线员。这个

    if ( no & !(no & (no - 1))) { 
    
    }
    

    应该是

    if ( no && !(no & (no - 1))) {
    
    }