不创建临时变量,实现两个数的交换
#include <stdio.h>
#include <stdlib.h>
int main(){
int a = 10;
int b = 20;
a = a^b;
b = a^b;
a = a^b;
printf("a=%d b=%d\n", a, b);
system("pause");
return 0;
}
这个代码主要运用了C语言中操作符的知识,具体是按位异或操作,按位异或操作主要的功能是将两个数中不同的数(按二进制)变为1,相同为0
例如:10 — 0000 1010
20 — 0001 0100
a=10^20=0001 1110
b=a^b=0000 1010
a=a^b=0001 0100
这样看起来就是将两个数进行了交换
求一个整数存储在内存中的二进制的1的个数
#include <stdio.h>
#include <stdlib.h>
int main(){
int num = 10;
int cout = 0;
while (num){
if (num % 2 == 1)
cout++;
num = num / 2;
}
printf("二进制中的1的个数=%d\n", cout);
system("pause");
return 0;
}
这个代码中的num=num/2 可以用num=num>>1
代替,因为在移位操作符中左移相当于乘二,右移相当于除以二
例如一下代码:
#include <stdio.h>
#include <stdlib.h>
int main(){
int num = 10;
int i = 0;
int cout = 0;
for (i = 0; i < 32; ++i){
if (((num >> i) & 1) == 1)
cout++;
}
printf("二进制中的1的个数=%d\n", cout);
system("pause");
return 0;
}
还有一个比较难想到的方法:
#include <stdio.h>
#include <stdlib.h>
int main(){
int num = 10;
int i = 0;
int cout = 0;
while (num){
cout++;
num = num&(num - 1);
}
printf("二进制中的1的个数=%d\n", cout);
system("pause");
return 0;
}