假定是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次全加.上麵的代碼可能需要調試一下,但原理應該就是這樣了.