位运算的简单应用(C实现)

详细理论请参考Matrix67!

//去掉最后一位,相当于除于2
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf ("%d\n", n>>1);
}
return 0;
}

//在最后加一个0,相当于乘于2
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf ("%d\n", n<<1);
}
return 0;
}

//在最后加一个1
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf ("%d\n", (n<<1)+1);
}
return 0;
}

//把最后一位变成1
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf ("%d\n", n|1);
}
return 0;
}

//把最后一位变成0
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf ("%d\n", (n|1)-1);
}
return 0;
}

//最后一位取反
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf ("%d\n", n^1);
}
return 0;
}

//把右数第k位变成1
#include <stdio.h>

int main() {
int n, k;
while (scanf("%d%d", &n, &k) != EOF) {
printf ("%d\n", (1<<(k-1))|n);
}
return 0;
}

//把右数第k位变成0
#include <stdio.h>

int main() {
int n, k;
while (scanf("%d%d", &n, &k) != EOF) {
printf ("%d\n", ~(1<<(k-1))&n);
}
return 0;
}

//右数第k位取反
#include <stdio.h>

int main() {
int n, k;
while (scanf("%d%d", &n, &k) != EOF) {
printf ("%d\n", (1<<(k-1))^n);
}
return 0;
}

//取末k位
#include <stdio.h>

int main() {
int n, k;
while (scanf("%d%d", &n, &k) != EOF) {
printf ("%d\n", ((1<<k)-1)&n);
}
return 0;
}

//取右数第k为
#include <stdio.h>

int main() {
int n, k;
while (scanf("%d%d", &n, &k) != EOF) {
printf ("%d\n", ((1<<(k-1))&n)>>(k-1));
//or printf ("%d\n", (n>>(k-1))&1);
}
return 0;
}

//把末k位变成1
#include <stdio.h>

int main() {
int n, k;
while (scanf("%d%d", &n, &k) != EOF) {
printf ("%d\n", ((1<<k)-1)|n);
}
return 0;
}

//把末k位取反
#include <stdio.h>

int main() {
int n, k;
while (scanf("%d%d", &n, &k) != EOF) {
printf ("%d\n", ((1<<k)-1)^n);
}
return 0;
}

//把右边连续的1变成0
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
if (n & 1) printf ("%d\n", n&(n+1));
else printf ("从右边起没有连续的1\n");
}
return 0;
}

//把右起第一个0变成1
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf ("%d\n", (n+1)|n);
}
return 0;
}


//把右边连续的0变成1
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
if (!(n & 1))printf ("%d\n", n|(n-1));
else printf ("从右边起没有连续的0\n");
}
return 0;
}


//取右边连续的1
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
if (n & 1) printf ("%d\n", ((n+1)^n)>>1);
else printf ("从右边起没有连续的1\n");
}
return 0;
}


//去掉右起第一个1的左边
#include <stdio.h>

int main() {
int n;
while (scanf("%d", &n) != EOF) {
printf ("%d\n", n&(n^(n-1)));
}
return 0;
}

 

    原文作者:位运算
    原文地址: http://www.cnblogs.com/try86/archive/2012/04/05/2432641.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞