Offoffoffoffer does not require addition, subtraction, multiplication, division, or addition.
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/59ac416b4b944300b617d4f7f111b215? Rp = 3 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Write a function and calculate the sum of two integers. The +,-, *, And/operators must not be used in the function.
Ideas
The question requires no four operations, so we can only think of bitwise operations. How can we use bitwise operations to calculate addition?
First, we can see that the sum of two numbers does not carry. This is actually the value of two numbers that are different or different.
Then we have to calculate the carry. We know that the binary system only needs to carry the carry only when it is the same as 1. If it is the same as 1, we can only get it through the & operation.
After the above conclusion is obtained, we can know that the entire addition process is a process of two numbers of different or and phase and left shift.
Class Solution {public: int Add (int num1, int num2) {int sum, carry; do {sum = num1 ^ num2; carry = (num1 & num2) <1; num1 = sum; num2 = carry;} while (num2); return num1 ;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source