How would you divide a number by 3 without using
The number may be signed or unsigned.
*
, /
, +
, -
, %
, operators?The number may be signed or unsigned.
There is a simple function I found here. but it's using the + operator, so you have to add the values with the bit-operators:
// replaces the + operator
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; }
No comments:
Post a Comment