计算非零整数二进制表示下_C程序,用于计算整数中的尾随零

计算非零整数二进制表示下

Problem statement: Write a C program to Count the Number of Trailing Zeroes in the binary representation of an Integer.

问题陈述:编写一个C程序以Integer的二进制表示形式计算尾随零的数量

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

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

Pre-requisite: Input number n

前提条件:输入数字n

Algorithm:

算法:

1)  Set count=0
2)  Do bit wise 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 Integer has trailing zero else don’t have
    Thus,
    IF
        n& 1 = =0
        count++
    ELSE
        Break; //no more trailing zero since current LSB is 1
    END IF-ELSE
3)  Right shift n by 1
    n=n>>1
4)  IF n==0
        Break
    ELSE
        REPEAT step 2, 3
5)  Print

Example with Explanation:

解释示例:

Trailing zeroes in 12: 12 → 00001100

12中的结尾零:12→00001100

    So first iteration:
    n=12 //00001100
    n & 1 =0 
    count=1
    n=n>>1 (n=6) //00000110

    So second iteration:
    n=6 //00000110
    n & 1 =0 
    count=2
    n=n>>1 (n=3) //00000011

    So third iteration:
    n=3 //00000011
    n & 1 =1 
    break
    print count=2
    No of trailing zeroes: 2

C implementation

C实现

#include <stdio.h>

int main()
{
	unsigned int n;
	printf("enter the integer\n");
	scanf("%d",&n);
	int count=0;
	while(n!=0){
		if(n & 1 == 1) //if current bit is 1
			break; //no more trailing zero
		n=n>>1; //right shift
		count++; //if trailing zero, increase count
	}

	printf("no of trailing zero ");
	//print no of trailing zero
	printf("in its binary representation: %d \n",count); 

	return 0;
}

Output (first run)

输出(首次运行)

enter the integer
12
no of trailing zero in its binary representation: 2

Output (second run)

输出(第二次运行)

enter the integer
13
no of trailing zero in its binary representation: 0


翻译自: https://www.includehelp.com/c-programs/count-the-number-of-trailing-zeroes-in-integer.aspx

计算非零整数二进制表示下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值