目前分類:隨手筆記 (3)

瀏覽方式: 標題列表 簡短摘要

Reference Link : http://offclassroom.com/off-classroom/cc/282-swap-variables-in-c-without-using-temporary-variable.html


Hello friends! Being a final year computer engineering student, I have gone through so many C programming logics as a preparation of Interview (unfortunately still haven't got a chance to face it :-)
Recently one of my friends cleared the first two rounds of aptitude & programming and then got a chance to face the interview. He was asked so many logical questions on C & C++ . One of those question was, “How many different methods do you know to swap two variables without using a temporary variable?”

From this question, we can't give a particular answer as there might be so many logical solutions that can be used to swap two variables. I certainly know three:

Method 1: Swap two variables using + & - operators

a = a+b;
b = a-b; 
a = a-b;

lets take a=10 & b=5,

a =  a+b = 10+5 = 15      so, a=15 & b=5
b = a-b = 15-5 = 10        so, a=15 & b=10
a = a-b = 15-10 = 5       so, a=5 & b=10

Thus a=5 & b=10, values are swapped.
This is the most popular method for swapping two variables but still this method has one drawback. If a and b are big and their addition is bigger than the size of integer than this might end up giving you wrong results.

Method 2 : Using X-OR (^) operator

a = a^b;
b = b^a;
a = a^b;

lets take a same example a=10 & b=5,

a = a^b = 10^5 = 15        so, a=15 & b=5
b = b^a = 5^15 = 10        so, a=15 & b=10
a = a^b =15^10 = 5         so, a=5 & b=10

Drawback of this method is that it will not work for floating-point values.

Method 3 : Using Pointers

We can overcome the drawback of Method 2 if we use pointers.

swap(int *a, int *b) 

*a = *a^*b;
*b = *b^*a;
*a = *a^*b;
}

We still have some problem with this method if use X-OR (^)
Now suppose, by mistake, your code passes the pointer to the same variable to this function. Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). 
One solution to this problem is to check if the numbers to be swapped are already equal to each other.

swap(int *a, int *b) 

if(*a!=*b) 

*a = *a^*b;
*b = *b^*a;
*a = *a^*b;

}

techdrew 發表在 痞客邦 留言(0) 人氣()

Formula:

 

1+4+9+25+...+n^2 = (n(n+1)(2n+1)) / 6

techdrew 發表在 痞客邦 留言(0) 人氣()

薛丁格的貓是奧地利物理學家埃爾溫·薛定諤用來解釋在宏觀情況下量力子學還不完整的假想性實驗

實驗內容大意:

1. 將一隻貓,放射性原子核,和一個毒氣瓶放到一個密閉的箱子裡

2.這個放射性原子核在一個小時內有50%的機率衰竭放出一個力子,而這個力子會啟動毒氣瓶殺死貓

 薛丁格的貓 

後面的一些研究有關連的量力子學得不完整提出的一些問題,相信大家也看不懂

但這個實驗牽扯到多世界理論,因為一小時候這裡面的貓有可能是死的,也有可能是活的

放射性原子核在一小時之內有可能衰弱也有可能維持正常

在還沒打開盒子之前有很多個未知數,而每個未知數牽扯到一個不同的世界

可是觀察者只能觀察到的結果只會有一種,也就只能進入一個世界(自己的那個)

 

這像實驗背後還有個意義,就是凡事都要去嘗試才有結果

如果只是一股腦的在猜測裡面的貓是死是活是沒有結論的

唯有把盒子打開才知道結果

 

之前看THE BIG BANG THEORY裡面有講到 覺得這實驗還滿有趣的

techdrew 發表在 痞客邦 留言(0) 人氣()