Method One: Program: #include <stdio.h>int count_one_bits (int t) {int i = 32;int count = 0;while (i>0) {if (t & 1 = = 1) {count ++;} t=t/2t = t >> 1;i-= 1;} return count;} int main () {int t = 0;printf ("Please enter an integer:"), scanf ("%d", &t), int ret=count_one_bits (t);p rintf ("count=%d\n", ret); return 0;} Method Two: Program: #include <stdio.h>int count_one_bits (int t) {int count = 0;while (t) {count++;t = t& (t-1);//The lowest bit is 1, the remainder is all 0, The cycle efficiency is high, there are several 1 cycles several times}return count;} int main () {int t = 0;printf ("Please enter an integer:"), scanf ("%d", &t), int ret=count_one_bits (t);p rintf ("count=%d\n", ret); return 0;} Result one: Please enter an integer: 15count=4 please press any key to continue ... Result two: Please enter an integer: -2count=31 please press any key to continue ...
This article is from the "Rock Owl" blog, please be sure to keep this source http://10742111.blog.51cto.com/10732111/1717837
Write a function to return the number of 1 in the parameter binary example: 15 0000 1111 4 1