Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

สลับค่าตัวเลข 2 ตัวด้วย Bitwise XOR ใน C (No Temp Variable)


โจทย์

สลับค่าตัวแปร 2 ตัวโดยไม่ใช้ตัวแปรชั่วคราว ใช้ Bitwise XOR (^)

หลักการ XOR Swap

a = a ^ b;
b = a ^ b;  // = (a^b)^b = a
a = a ^ b;  // = (a^b)^a = b

อัลกอริทึม

  1. รับค่า a, b
  2. a = a ^ b
  3. b = a ^ b
  4. a = a ^ b
  5. แสดงผล

โปรแกรมตัวอย่าง

#include <stdio.h>
int main() {
    int a, b;
    printf("Enter a and b: ");
    scanf("%d %d", &a, &b);
    
    printf("Before: a=%d, b=%d\n", a, b);
    
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    
    printf("After:  a=%d, b=%d\n", a, b);
    return 0;
}

ผลลัพธ์ + อธิบาย Binary

enter the values for a and b: 24 56
value of a=24 and b=56 before swap
value of a=56 and b=24 after swap

Explanation:
a=24  -> binary 011000
b=56  -> binary 111000
a^b   -> 100000
b=a^b -> 011000 (24)
a=a^b -> 111000 (56)