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;
      }
}
相关推荐
水饺编程11 小时前
第2章:Linux 基础,exit 命令
linux·c语言·汇编
小郎君65811 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
邵奈一12 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS10012 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法
shehuiyuelaiyuehao12 小时前
算法56,重排链表
数据结构·算法·链表
qq_4523962313 小时前
第四篇:《索引原理与实战:B-tree、Hash、GIN、GiST、BRIN》
算法·哈希算法·gin
西索斯coding13 小时前
Qwen3-Max 与 Qwen-Plus:60 个真实修复任务评测方案
大数据·网络·算法·ai
INGNIGHT13 小时前
440 · 背包问题(三)(无限次数)
算法·leetcode·动态规划
suhan13 小时前
【数据结构】七、查找:1.查找的概念、线性结构查找(顺序、折半(二分)、插值、稠密、分块、倒排)
数据结构·算法·排序算法