C语言一些逆置算法

目录

整数逆置

数组逆置

矩阵转置


整数逆置

如7234变为4327

复制代码
int Reversed(int n){
	int x,reversed_n=0;
	while(n!=0){
		x=n%10;		
		reversed_n=reversed_n*10+x;
		n=n/10;
	}
	return reversed_n;
}

数组逆置

将数组{1,2,3,4,5,6}逆置为{6,5,4,3,2,1}

复制代码
void Reverse(int a[],int l,int r){
	while(l<r){
		int temp;
		temp=a[l];
		a[l]=a[r];
		a[r]=temp;
		l++;
		r--;
	}	
}

利用数组逆置的性质,然后我们知道(A-1B-1)-1 = BA ,可以用这个性质实现循环左移函数

cpp 复制代码
void Converse(int a[],int num,int len){	//num是移动位数,len是数组长度
	Reverse(a,0,num-1);    //A逆
	Reverse(a,num,len-1);    //B逆
	Reverse(a,0,len-1);    //然后AB整体逆就能得到BA
} 
//主函数
int a[8]={1,2,3,4,5,6,7,8};
Converse(a,3,8);	//循环左移三位

矩阵转置

以对角线为对称交换两个元素

cpp 复制代码
int temp;
for (i = 0; i < n; i++) {		//两个for循环遍历上三角元素
     for (j = i + 1; j < n; j++) {	//上三角与下三角交换
          temp = a[i][j];
          a[i][j] = a[j][i]; 
          a[j][i] = temp;
      }
}
相关推荐
电科_银尘5 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴8 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David8 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
戊本菌10 小时前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
Pniubi11 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK11 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
上海潭龙东海科技有限公司13 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
嵌入式 Linux手记13 小时前
一块内存,三种解释:union 的真实用法
linux·c语言·驱动开发·嵌入式
阿庆_AI研发工程师15 小时前
Stanford CS336 Lecture 10:大语言模型推理与性能优化
算法
用户73416810354815 小时前
基于MindSpore的深度残差收缩网络程序
算法