Offoffoffoffer does not require addition, subtraction, multiplication, division, or addition.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.