This is also a face-to-face question. The interviewer asked how to divide the original question by 3 by shift and addition or subtraction. Here, we will slightly expand it to implement the unsigned integer division, however, the returned value is also an unsigned integer.
Method 1: similar to the division operation of primary school learning, the division operation starts from the high point minus the division number. Here, the Division is shifted left to align with the division number. The operator also needs to move left before the subtraction. The Code is as follows.
#include <iostream>using namespace std;unsigned int divide(unsigned int a, unsigned int b){if(0 == b)__asm int 0unsigned int c = 1, d = 0, _b = b;while(a >= b){c <<= 1;b <<= 1;}b >>= 1;c >>= 1;while(b >= _b){if(a >= b){a -= b;d += c;}b >>= 1;c >>= 1;}return d;}int main(){unsigned int in, out;cin>>in;cin>>out;cout<<divide(in, out)<<endl;return 0;}
Method 2: subtract the divisor with the divisor, and Add 1 to the result of every successful subtraction. The other code remains unchanged. The divide function code is changed to the following.
unsigned int divide(unsigned int a, unsigned int b){if(0 == b)__asm int 0unsigned int c = 0;while(a >= b){a -= b;c++;}return c;}
Method 3: Use magic number. The Code is as follows.
#include <iostream>using namespace std;int divide3(int a){return ((__int64)a * 0xAAAAAAAB) >>33;}int main(){int in;cin>>in;cout<<divide3(in)<<endl;return 0;}
The principle of the magic number in method 3 is to implement the division operation of 32-bit divisor by multiplication. the compiler will multiply the divisor by a 32-bit reciprocal to form a 64-bit number, among them, the low 32-bit is the remainder, and the high 32-bit is the result we need. Below are some common magic numbers. For example, 0xaaaaaaab represents 2/3, and 0xcccccccd represents 4/5, you can search for related content on the Internet. The Code dividing the magic number by 5 is as follows.
#include <iostream>using namespace std;int divide5(int a){return ((__int64)a * 0xCCCCCCCD) >>34;}int main(){int in;cin>>in;cout<<divide5(in)<<endl;return 0;}