算法积累二(位操作部分) Algorithms - Bit Operation
Achieve Multiplication without *
Simulate multiplication with bit operation. Actually each int could be represent by binary format, like 10 == 1010, 4 == 0100, so it can use distributive law of multiplication. 10 = 8 + 2, so 10 4 = (8+2) 4 = 2^34 + 2\4
123456789101112131415161718192021222324int multiply(int a, int b){bool sign = true;if(a<0 && b < 0) {a = -a;b = -b;}else if(a < 0){sign = false;a = -a;}else if(b < 0){sign = false;b = -b;}int c = 0;while(b > 0){if((b & 1) == 1){c += a;}b >> 1;a << 1; // a * 2}return c;}
Some common bit operations
Setting a bit
1number |= 1<<x;Clearing a bit
1number &= ~(1<<x);Toggling a bit
1number ^= 1<<x;Checking a bit
1bit = (number >> x) & 1;Changing the nth bit to X(0 or 1)
1number ^= (-x ^ number) & (1 << n);In computer, the negativative number is represented by complemental code(补码)