How to achieve summation in Java without arithmetic operator
This article mainly introduces the relevant knowledge of "how to achieve summation without arithmetic operators in Java". The editor shows you the operation process through actual cases. The method of operation is simple and fast, and it is practical. I hope this article "how to achieve summation without arithmetic operators in Java" can help you solve the problem.
The title says that arithmetic operators cannot be used, so we can only start with logical operators and shift operators.
We know that the ^ (XOR) operation is a carry-free sum of two numbers, and if the addition of two numbers does not produce carry, then the sum is the sum of two numbers. This is the key to solving the problem. Generally speaking, the addition of two numbers will produce carry, and in order to get the correct sum, we should add carry on the basis of "no carry sum", then we should first get carry. We know that when the corresponding position of the two numbers is 1, there will be carry, that is, under the condition of the corresponding position A&B==1, we can get the carry of each bit, but the carry is to add this 1 to the corresponding higher bit, so we move the whole carry to the left, and then add it to the "sum of no carry" obtained before, we can get the sum of two numbers.
We find that we can infinitely nest dolls here. In order to get the sum of "no carry sum" and "generated carry", then treat these two numbers as new numbers and sum them. Also repeat the previous operation, until the two numbers can not produce carry, you can directly through the ^ operation to get the result.
Suppose we find the value of 23 + 16.
According to the above ideas, we can easily write code.
Public static int addAB (int A, int B) {/ / when the carry generated by two numbers is 0, exit the loop and return its carry-free sum, which is the result while ((A & B)! = 0) {int int B = A ^ B / no carry sum int AB = (A & B)