回複:計算機程序題

假定是32位:

void fulladd(int a, int b, int& sum, int& carry) {
if (a == 0 && b ==0) {
sum = carry = 0;
} else if (a == 1 && b == 1) {
sum = carry = 1;
} else {
sum = 1; carry = 0;
}
}

... get n

int sum, carry = 0;

for (int count = 0xFFFFFFFF; count&1; count = count>>1) {
fulladd(n&1, 1, sum, carry);
n = (sum 1);
}

if (carry == 1) cout else cout
基本上就是做32次全加.上麵的代碼可能需要調試一下,但原理應該就是這樣了.

所有跟帖: 

可以快一點兒 -butdie- 給 butdie 發送悄悄話 butdie 的博客首頁 (255 bytes) () 12/22/2007 postreply 01:37:50

請您先登陸,再發跟帖!