方法一:
- #include
- int count_diff_bit(int m, int n)
- {
- int i = 0;
- int c = 0;//计数器
- for (i = 0; i < 32; i++)
- {
- if ((m & 1) != (n & 1))
- {
- c++;
- }
- m >>= 1;
- n >>= 1;
- }
- return c;
- }
- int main()
- {
- int m = 0;
- int n = 0;
- scanf("%d %d",&m, &n);
- int len = count_diff_bit(m, n);
- printf("%d\n", len);
- return 0;
- }
方法二:
- #include
- int count_diff_bit(int m, int n)
- {
- int c = 0;//计数器
- int tmp = m ^ n;//二进制的异或
- //统计tmp的二进制位中有多少个1:
- while (tmp)
- {
- tmp = tmp & (tmp - 1);
- c++;
- }
- return c;
- }
- int main()
- {
- int m = 0;
- int n = 0;
- scanf("%d %d",&m, &n);
- int len = count_diff_bit(m, n);
- printf("%d\n", len);
- return 0;
- }
或不写成函数形式:
- #include
- int main()
- {
- int m = 0;
- int n = 0;
- scanf("%d %d", &m, &n);
- int c = 0;
- int tmp = m ^ n;
- while (tmp)
- {
- tmp = tmp & (tmp - 1);
- c++;
- }
- printf("%d\n", c);
- return 0;
- }