编写函数,用简单的字符进行编译

编写函数
int detectBits(int x);
判断一个int类型数据的二进制表达是否所有奇数都为1(最低位即0位位偶数,最高位即31位为奇数)
示例:
detectBits(4294967293)=0

判断最低位为0,最高位为1:
有帮助望采纳

#include <stdio.h>
#include <string.h>

int main()
{
    printf("%d\n", detectBits(4294967293));
    printf("%d\n", detectBits(-1));
    printf("%d\n", detectBits(-2));
}
int detectBits(int x)
{
    if ((x & 0x80000001) ^ 0x80000000)
        return 0;
    return 1;
}

用itoa将整型转换为二进制字符串,然后比较奇数下标对应值是否为'1'即可

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int a, i, b = 1;
    scanf("%d", &a);
    char c[40] = { 0 };
    itoa(a, c, 2);
    int len = strlen(c);
    for (i = 1; i<len; i += 2)
        if (c[i] == ‘0‘)
        {
            b = 0;
            break;
        }
    if (b == 0)
        printf("不是所有奇数位都为1");
    else
        printf("所有奇数位都为1");
    return 0;

}

处理二进制当然是要用位运算了。
如果是从0位到31位的奇数位都判断是

#include <stdio.h>
#include <stdlib.h>
int detectBits(int x)
{
    int t = 0xAAAAAAAA;
    return (x & t) == t;
}
int main()
{
    int n;
    scanf("%d", &n);
    if (detectBits(n))
        printf("所有奇数位都为1");
    else
        printf("不是所有奇数位都为1");
    return 0;
}

如果正数的高位不需要判断

#include <stdio.h>
#include <stdlib.h>
int detectBits(int x)
{
    if (x<0)
    {
        int t = 0xAAAAAAAA;
        return (x & t) == t;
    }
    else
    {
        if (x<=1) return 0;
        int t = 0b10;
        while (t<=x && t>0)
        {
            if ((x & t) == 0)
                return 0;
            t <<= 2;
        }
        return 1;
    }

}
int main()
{
    int n;
    scanf("%d", &n);
    if (detectBits(n))
        printf("所有奇数位都为1");
    else
        printf("不是所有奇数位都为1");
    return 0;
}

img