Original address: http://blog.csdn.net/luckyxiaoqiang/article/details/6886489
The idea of bit operation can be applied to many places, here is a simple summary of using bit arithmetic to realize the arithmetic of integer.
1. Integer addition
[CPP] View plain copy int add (int a,int b) { for (int i = 1; i; i <<= 1) if (b & i) for (int j = i; j; j <<= 1) if (a & j) a &= ~j; else {a |= j; break;} return a ; } My main idea is to use the a+1 bit operation is the leftmost (starting from the No. 0 bit to the left) continuous 1 to 0, originally a 0 of the position of the lowest that bit into 1.
Add 1 to the different bits, that is, from the corresponding bit start to the left, the right is unchanged.
Here is an online idea, I think this is better:
[CPP] view plain copy int Add (int a,int b) {if (b = = 0) return a;//when no rounding is done int Sum,carry ; sum = a ^ b;//complete the first step without carrying the addition operation Carry= (A & B) << 1;//complete the second step carry and left-shift operation return ADD (Sum,carry);//recursive, add I'll simplify:
[CPP] view plain copy int Add (int a,int b) {return B? Add (a ^ B, (A & B) <<1): A; The idea above is not to add the carry, and then add to the carry, with recursion, the carry will become 0, recursive end.
2. Integer subtraction
This is the same as addition, first take the complement of the meiosis, and then Add.
[CPP] view plain copy int minus (int a,int b) {for (int i = 1; I && (b & i) ==0); I < ; <= 1); for (int i <<= 1; i; I <<=1) b ^= i; Return Add (A, b); }
3. Integer multiplication
Multiplication is written as a multiplier (2^0) *k0 + (2^1) *k1 + (2 ^2) *k2 + ... + (2^31) *k31, where Ki is 0 or 1, then the bitwise operation and addition can be used.
[CPP] View plain copy Int mul (int a,int b) { int ans = 0; for (int i = 1; i; i <<= 1, a <<= 1) if (b & i) &n