对于给定的正数,我们需要将数字除以3,而不使用任何这些*,/,+,-%运算符
例子:
Input : 48
Output : 16
Input : 16
Output : 5
算法
- 取一个数字num,sum = 0
- while(num> 3),将数字左移两位,并且sum = add(num >> 2,sum)。创建一个函数add(x,y)以按位运算符将两个数相加
- 取x,y
- 运行do while循环,直到a不为零
- a = x&y,b = x ^ y ;, y = b;
- 在终止循环返回值b之后,得出x和y的和
- 取num与3的按位与
对于新的num = add(num >> 2,num&3) - 在终止while循环后,打印得出最终结果的和值。
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 i.e, 2
Now sum will be 2
num = (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 (this value is returned)
num = (shift the number(00000100) by 2 bits) + (number BITWISE AND 3)
num = 1 + 0
ie remainder = 1
// C++ program for divided a number by
// 3 without using operator
#include
using namespace std;
// A function to add 2 numbers without using +
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;
}
// Function to divide by 3
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;
}
// Driver program
int main(void)
{
int num = 48;
cout << "The number divided by 3 is ";
cout << divideby3(num);
return 0;
}
输出:
The number divided by 3 is 16