Problem
Divide a number by 3 without using any of operators (%,/,*)
Solution
Method 1
int divideby3 (int num) { int sum = 0; while (num > 3) { sum += num >> 2; num = (num >> 2) + (num & 3); } if (num == 3) ++sum; return sum; }
Dry running the above method :
For example if your number is 10 then convert to binary
10=>00001010
if 10 > 3 then shift the binary number 2 bits
Now num will be 00000010 ie, 2
Now sum will be 2
num=(right shift the number by 2 bits)+(number BITWISE AND 3)
num= 2+2
Now the number will be 4 then, 4>3 => true so loop will be repeated
4=>00000100 then shift the binary number 2 bits
Now sum=2+1 ie, sum=3
num=(shift the number(00000100) by 2 bits)+(number BITWISE AND 3)
num=1+0
ie remainder=1
Thanks.
0 comments:
Post a Comment