+ 1
a program to swap values of two numbers withiout using a third variable
9 Antworten
+ 4
Answer without integer overflow (in comparison to others, that use multiplication/division or addition/subtraction) and only 1 arithmetic operator:
step. state of variable (a, b)
a = a ^ b a ^ b b
b = a ^ b a ^ b a
a = a ^ b b a
+ 2
good question
let a b be numbers
step. state of variable(a,b)
a=a*b ab b
b=a/b ab a
a=a/b b a
+ 1
Yeah, one of the challenges does that with addition and subtraction. Also, pls be aware that this requires the values to be much smaller than the actual limits they can hold as addition and especially multiplication enlarge values. Also doing this on signed and unsigned data types may result in hitting these limits easily.
0
a=a+b;
b=a-b;
a=a-b;
first add value of a and b and store into a now a containing value of a and b then subtract value of b from a and assign this value to b now b containing value of a then subtract value of b from a and u will get value of b because b was containing value of a
0
@Marat: Very nice answer! :-)
0
@Marat: Is there a general solution for the problem? Bitwise operators only work on integer types...
0
@Stefan: you can use type dereferencing to integer types with the same size:
- for float a and b:
*(int*)&a = *(int*)&a ^ *(int*)&b;
*(int*)&b = *(int*)&a ^ *(int*)&b;
*(int*)&a = *(int*)&a ^ *(int*)&b;
- for double a and b just change "int" to "long long" in previous code.
0
@Stefan: also you can write the more generic function with some specialization magic ;)
template<class T> struct ID { typedef T I; };
template<> struct ID<float> { typedef int I; };
template<> struct ID<double> { typedef long long I; };
template<class T>
void swap(T& a, T&b) {
typedef typename ID<T>::I* D;
*(D)&a = *(D)&a ^ *(D)&b;
*(D)&b = *(D)&a ^ *(D)&b;
*(D)&a = *(D)&a ^ *(D)&b;
}
0
@Marat: Yeah, it's even applicable for arbitrary bit patterns (objects and such) as long as you turn them into an array of std::uint8_t.