+ 1

a program to swap values of two numbers withiout using a third variable

3rd Aug 2016, 5:19 PM
Sudeep Juno Soreng
9 Respuestas
+ 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
3rd Aug 2016, 7:01 PM
Marat
Marat - avatar
+ 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
3rd Aug 2016, 5:27 PM
Praveen Jayakumar
Praveen Jayakumar - avatar
+ 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.
3rd Aug 2016, 5:36 PM
Stefan
Stefan - avatar
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
3rd Aug 2016, 7:13 PM
sachin tomar
sachin tomar - avatar
0
@Marat: Very nice answer! :-)
3rd Aug 2016, 7:40 PM
Stefan
Stefan - avatar
0
@Marat: Is there a general solution for the problem? Bitwise operators only work on integer types...
3rd Aug 2016, 8:21 PM
Stefan
Stefan - avatar
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.
3rd Aug 2016, 9:39 PM
Marat
Marat - avatar
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; }
3rd Aug 2016, 9:59 PM
Marat
Marat - avatar
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.
3rd Aug 2016, 10:01 PM
Stefan
Stefan - avatar