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;
      }
}
相关推荐
春风解人意3 小时前
从零开始学习嵌入式P32----网络基础之TCP
c语言·网络·学习·tcp/ip
政企项目老覃5 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
是隼人5 小时前
buuctf-pwn inndy_echo(32位fmt)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
淡海水5 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR5 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵6 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽6 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2086 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
刃神太酷啦6 小时前
Redis 进阶核心:持久化 (RDB/AOF)、事务与主从复制全解析----《Hello Redis!》(5)
linux·c语言·数据库·c++·redis·缓存·bootstrap