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;
      }
}
相关推荐
sali-tec2 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
小明说Java2 小时前
常见排序算法的实现
数据结构·算法·排序算法
行云流水20193 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
smj2302_796826525 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme5 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5126 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8246 小时前
计数if|
算法
a伊雪6 小时前
c++ 引用参数
c++·算法
程序员Jared7 小时前
深入浅出C语言——程序环境和预处理
c语言
应茶茶7 小时前
从 C 到 C++:详解不定参数的两种实现方式(va_args 与参数包)
c语言·开发语言·c++