#include<stdio.h> int numberOf1_solution1(int n)/*将一个正数以此向右移一位,与1做与运算。直到这个数为零*/ { int count = 0; while (n) { if (n&1) count++; n=n >> 1; } return count; } int numberOf1_solution2(int n)/*将1以此向右移动以为,与一个数(正负数均可)做与运算,直到1出现上溢为止*/ { int count = 0, i = 1; while (i) { if (n&i) count++; i = i << 1; } return count; } int numberOf1_solution3(int n)/*将一个数减去1后再与本身相与。便可降低一个1,利用这个原理求1的个数*/ { int count = 0; while (n) { n = (n - 1)&n; count++; } return count; } int main() { printf("%d\n",numberOf1_solution3(5)); return 0; }
时间: 2024-10-05 18:08:01