位运算实现两个整数读交换_C程序使用位运算符交换两个整数

位运算实现两个整数读交换

Problem statement: Write a C program to swap two integers using bitwise operators without using any temporary variable.

问题陈述:编写一个C程序以使用按位运算符交换两个整数,而不使用任何临时变量

Algorithm:

算法:

  1. Let n1 and n2 be two numbers to be swapped.

    令n1和n2是要交换的两个数字。

  2. Update n1 to n1^n2, i.e., n1=n1^n2

    更新N1到N1 N2 ^,即N1 = N1 N2 ^

  3. Update n2 to n1^n2, i.e., n2=n1^n2 //n1 is already updated in previous step, use the updated value.

    将n2更新为n1 ^ n2 ,即n2 = n1 ^ n2 // n1已在上一步中更新,请使用更新后的值。

  4. Again update n1 to n1^n2, i.e., n1=n1^n2 //n2 already updated in previous step.

    再次更新N1到N1 N2 ^,即N1 = N1 N2 ^ // N2已经更新上一步。

This results in swapping as n1 contains new value of n2 and vice versa.

这导致交换,因为n1包含n2的新值,反之亦然

Reason:

原因:

    n1=n1^n2; //statement1
    n2=n1^n2; //statement2
    n1=n1^n2; //statement3

    At statement 2 replace n1 by stamen 1,
    n2  = (n1^n2) ^ n2
        = n1^ (n2^n2) //XOR follows associative property
        = n1^0 // (n2^n2=0)
        = n1

    At statement 3 replace n1, n2 by statement 1, 2
    n1  = (n1^n2) ^ n1 //n2=n1 just found previously
        = (n2^n1) ^n1 //XOR follows commutative property
        = n2^ (n1^n1)
        = n2^ 0
        = n2

    Thus n1 & n2 is swapped

Example with explanation

带说明的例子

Let two numbers be
n1= 5 //0000 0101
n2= 8 //0000 1000

Let's perform the aforementioned steps:
1.  n1=n1^n2
    n1= 0000 0101 ^ 0000 1000 = 0000 1101
2.  n2=n1^n2
    n2= 0000 1101 ^ 0000 1000= 0000 0101 //5=n1(original value of n1) actually
3.  n1= n1^ n2
    n1= 0000 1101 ^ 0000 0101 = 0000 1000 //8 =n2 (original value of n2) actually

用位运算符交换两个整数的C实现 (C implementation to swap two Integers using Bitwise Operators)

#include <stdio.h>

int main()
{   
	int n1,n2;
	printf("enter two numbers\n");
	scanf("%d %d",&n1,&n2);
	printf("before swapping...\n");
	printf("first no is %d, second no %d\n",n1,n2);

	//swapping using bitwise operators

	n1=n1^n2;
	n2=n1^n2;
	n1=n1^n2;

	//n1 & n2 is swapped
	printf("after swapping...\n");
	printf("first no is %d, second no %d\n",n1,n2);

	return 0;
}

Output

输出量

enter two numbers
5 7
before swapping...
first no is 5, second no 7
after swapping...
first no is 7, second no 5  


翻译自: https://www.includehelp.com/c-programs/swap-two-integers-using-bitwise-operators.aspx

位运算实现两个整数读交换

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值