c语言给定一个非空整数数组_C程序检查给定整数的所有位是否为一(1)

c语言给定一个非空整数数组

Problem statement: Write a C Program to check if all the bits of a given integer is one (1).

问题陈述:编写一个C程序来检查给定整数的所有位是否都是一(1)

Solution: We can use bitwise operator here to solve the problem.

解决方案:我们可以在这里使用按位运算符来解决问题。

Pre-requisite: Input number n

前提条件 :输入数字n

Algorithm:

算法:

1)  Do Bitwise AND with n and 1. 
    n & 1
    
    let n be a7a6a5a4a3a2a1a0
    1->00000001
    So doing bitwise AND (refer to published article on bitwise operators) 
    will result in all bits 0 except the LSB which will be a0. 
    If a0 is 0 then the all bits are not set
    Thus,
    IF
        n & 1 ==0
        Print that all bits are not same
    ELSE
        Right shift n by 1
        n=n>>1
    END IF-ELSE

2)  IF n==0
        Print that all bits are set
    ELSE
        REPEAT step 1

Example with Explanation:

解释示例:

Checking for 12
12-> 00001100

So first iteration:
n=12 //00001100
n & 1 ==0 
so print that all bits are not set

Checking for 7
7->00000111

So first iteration:
n=7 //00000111
n & 1 =1
n=n>>1 (n=3) //00000011

So second iteration:
n=3 //00000011
n & 1 =1
n=n>>1 (n=1) //00000001

So third iteration:
n=1 //00000001
n & 1 =1
n=n>>1 (n=0) //00000000

So, All bits are set


C implementation

C实现

#include <stdio.h>

int main()
{
	unsigned int n;
	printf("enter the integer\n");
	scanf("%d",&n);

	while(n>0){
		int temp=n&1;
		if(temp == 0){ //if any bit not set
			printf("all bits are not set\n");
			return 0;
		}
		n=n>>1; //right shift operator
	}

	printf("all bits are set ");
	printf("in its binary representation\n");

	return 0;
}

Output

输出量

First run:
enter the integer
12
all bits are not set

Second run:
enter the integer
7
all bits are set in its binary representation


翻译自: https://www.includehelp.com/c-programs/check-if-all-the-bits-of-a-given-integer-is-one-1.aspx

c语言给定一个非空整数数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值