question
Divide a number by 3 without using
The number may be signed or unsigned.
+
, -
, *
, /
or %
operators.
The number may be signed or unsigned.
Think of bit-operators that can help you carry out operations.
There are a few solutions for this, the most accepted answer though has been copied from a StackOverflow question below:
This works because:
1. n = 4 * a + b
2. n / 3 = a + (a + b) / 3
3. So sum += a, n = a + b, and iterate.
4. When a == 0 (n < 4), sum += floor(n / 3); i.e. 1, if n == 3, else 0
Again please view the original question and answer from StackOverflow.
Thoughts or alternate solution? Let us know in the comments below!
int add(int x, int y) {
int a, b;
do {
a = x & y;
b = x ^ y;
x = a << 1;
y = b;
} while (a);
return b;
}
int divideby3 (int num) {
int sum = 0;
while (num > 3) {
sum = add(num >> 2, sum);
num = add(num >> 2, num & 3);
}
if (num == 3)
sum = add(sum, 1);
return sum;
}
This works because:
1. n = 4 * a + b
2. n / 3 = a + (a + b) / 3
3. So sum += a, n = a + b, and iterate.
4. When a == 0 (n < 4), sum += floor(n / 3); i.e. 1, if n == 3, else 0
Again please view the original question and answer from StackOverflow.
Thoughts or alternate solution? Let us know in the comments below!