c++ - 如何不使用第三个变量,交换两个char的值
PHP中文网
PHP中文网 2017-04-17 14:44:40
0
7
610

对于int a 和 int b
可以使用下面的代码 互换a和b的值

void function(inta, int
b){
        a=a+b;
        b=a-b;
        a=a-b;
    }

如果交换 两个char类型,该怎么办喃?

PHP中文网
PHP中文网

认证0级讲师

reply all(7)
大家讲道理

General

The char type is actually a byte type, with only one byte, so the issue of overflow must be considered, and addition cannot be used.
Of course, in fact, int types cannot be exchanged by addition and subtraction. Using 位异或 is a general method.

void main()
{
    char a = 'x';
    char b = 'y';
    a ^= b;
    b ^= b;
    a ^= b;
    std::cout << "a:"<< a <<"-b:" << b<<std::endl;
    //a:y-b:x
}

Special

If you are on the windows platform, you can use built-in functions

void main()
{
    char a = 'x';
    char b = 'y';
    b=InterlockedExchange8(&a, b);
    std::cout << "a:"<< a <<"-b:" << b<<std::endl;
    //a:y-b:x
}

Extended

You can use assembly to do it directly by yourself

void main()
{
    char a = 'x';
    char b = 'y';
    __asm
    {
        mov al,a
        xchg al,b
        mov a,al
    }
    std::cout << "a:"<< a <<"-b:" << b<<std::endl;
    //a:y-b:x
}
阿神

charIt’s actually int

#include <stdio.h>

void swap(char *a, char *b) {
  *a = *a ^ *b;
  *b = *a ^ *b;
  *a = *a ^ *b;
}

int main() {
  char a = 'x';
  char b = 'y';

  printf("交换前: a='%c', b='%c'.\n", a, b);
  swap(&a, &b);
  printf("交换后: a='%c', b='%c'.\n", a, b);
  return 0;
}

Output

交换前: a='x', b='y'.
交换后: a='y', b='x'.
刘奇

Remember, bit operations are used. I forgot the details

Mark it and wait for the master to answer it

伊谢尔伦
void function(char &a, char &b){
  if(a==b) return ;
  a = a ^ b;
  b = b ^ a;
  a = a ^ b;
}

In fact, for 2 integers (including char), using XOR to exchange variables is better than using addition and subtraction (there is no overflow problem)

Ty80

Using XOR is not efficient/space-saving, and the result is wrong when two char are equal. For example:

char a = 'f';
char b = 'f';
char a = b ^ a // now a == 0

And when it comes to assembly, there is no extra space. Please refer to Why it is wrong to use XOR to exchange variables

伊谢尔伦

Char is also an integer in nature

伊谢尔伦

Type conversion is required
So when converting char type data,
must refer to an intermediate third variable of type int
So the question you asked is contradictory. Can't be achieved.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!