C程序对整数中设置为1的位数进行计数
生活随笔
收集整理的這篇文章主要介紹了
C程序对整数中设置为1的位数进行计数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Problem statement: Write a C program to count number of bits set to 1 in an Integer.
問題陳述:編寫一個C程序來計算Integer中設置為1的位數 。
Solution: We can use bitwise operator here to solve the problem.
解決方案:我們可以在這里使用按位運算符來解決問題。
Pre-requisite: Input number n
前提條件 :輸入數字n
Algorithm:
算法:
1) Set count=12) Do bit wise AND with n and 1. n & 1let n be a7a6a5a4a3a2a1a01->00000001So 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 setThus,IFn& 1 == 1count++;END IFRight shift n by 1n=n>>13) IF n==0Print countELSEREPEAT step 1, 2Example with Explanation:
解釋示例:
Checking for 7 7->00000111Initially, count=0So first iteration: n=7 //00000111 n & 1 =1 so , count=1 n=n>>1 (n=3) //00000011So second iteration: n=3 //00000011 n & 1 =1 count=2 n=n>>1 (n=1) //00000001So third iteration: n=1 //00000001 n & 1 =1 count=3 n=n>>1 (n=0) //00000000 So, Print count, 3 .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}} .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}}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 1count++;//increase count}n=n>>1;//right shift}printf("no of bits those are 1 ");printf("in its binary representation: %d\n",count);return 0; }Output
輸出量
First run: enter the integer 7 no of bits those are 1 in its binary representation: 3Second run: enter the integer 12 no of bits those are 1 in its binary representation: 2翻譯自: https://www.includehelp.com/c-programs/count-number-of-bits-set-to-1-in-an-integer.aspx
總結
以上是生活随笔為你收集整理的C程序对整数中设置为1的位数进行计数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: synchronized 中的 4 个优
- 下一篇: 为什么HashMap会产生死循环?