【C】位运算典型例题

32位倒序

在32位机器上25这个值包含下列各位:
00000000000000000000000000011001
翻转后:(2550136832)
10011000000000000000000000000000
程序结果返回:
2550136832

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>

int Tra(int n,int sn) {
	int tmp;
	int sum = 0;
	for (int i = 0; i<32; n /= sn,++i) {
		tmp = n % sn;
		sum = sum * sn + tmp;
	}
	printf("%u", sum);
	printf("\n");
}
int main() {
	Tra(25, 2);
	system("pause");
}

这里给出的固定值;可以自行进制更换倒序

一组数据中只有一个数字出现了一次。其他所有数字都是成对出现的。

请找出这个数字。(使用位运算)
…异或 。。。。。。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>

int main() {
	int arr[9] = { 1,2,3,4,5,4,3,2,1 };
	int a = 0;
	for (int i = 0; i < 9; ++i) {
		a ^= arr[i];
	}
	printf("%d\n", a);
	system("pause");
 }

有一个字符数组的内容为:“student a am i”

请你将数组的内容改为"i am a student".
要求:
不能使用库函数。
只能开辟有限个空间(空间个数和字符串的长度无关)。

student a am i
i ma a tneduts
i am a student

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
//逆序函数
void Exchange(char* str, int start, int end) {
	char tmp;
	int i, j;
	for (i = start, j = end - 1; i < j; ++i, --j) {
		tmp = str[i];
		str[i] = str[j];
		str[j] = tmp;
	}
}

int main() {
	char str[] = "There are trees and branches in the mountains";
	int start = 0;
	int i = 0;
	for (; str[i]; ++i) {
		if (str[i] == ' ') {
			Exchange(str, start, i);
			start = i + 1;
		}
	}
	Exchange(str, start, i);
	Exchange(str, 0, i);
	puts(str);
	system("pause");
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值