昨天在leetcode做题的时候做到了371,原题是这样的: 371. Sum of Two Integers Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. 因为之前完全没有在实际练习中使用过位运算,所以刚看到这道题目的时候我的第一反应是 1.用乘除代替加减,但是一想,
//求两个数中不同的位的个数 #include <stdio.h> int count_different(int a, int b) { int count = 0; int c = a^b; //a,b中不同的位即为1 while (c) { count++; c = c&(c - 1); //把c中最后一个1去掉 } return count; } int main() { printf("%d\n", count_different(3,8)); //3 p