Showing posts with label variables. Show all posts
Showing posts with label variables. Show all posts

Sunday, September 15, 2024

Swap two variables without using extra variables

In C++, you can swap two variables without using extra variables using the same arithmetic or bitwise XOR methods. Here's how you can do it:

1. Using Arithmetic Operations:

#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 10;

    a = a + b;  // Step 1: a becomes 15 (5 + 10)
    b = a - b;  // Step 2: b becomes 5 (15 - 10)
    a = a - b;  // Step 3: a becomes 10 (15 - 5)

    cout << "a = " << a << ", b = " << b << endl;
    return 0;
}


2. Using Bitwise XOR:

#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 10;

    a = a ^ b;  // Step 1: a becomes 15 (binary XOR of 5 and 10)
    b = a ^ b;  // Step 2: b becomes 5
    a = a ^ b;  // Step 3: a becomes 10

    cout << "a = " << a << ", b = " << b << endl;
    return 0;
}

Why does the Dijkstra algorithm fail to detect negative cycles?

Dijkstra’s algorithm fails to detect and correctly handle negative weight cycles due to the way it processes nodes and updates the shortest ...