Implement addition: Do not use addition, subtraction, multiplication, division

Source: Internet
Author: User

From: http://sllovewsy149.blog.163.com/blog/static/108734178201245114626125/

Reference: http://blog.csdn.net/morewindows/article/details/8710737

Q: Write an algorithm to add two numbers, but do not use addition (+) or other arithmetic operations.

A: First, consider how we add two decimal numbers.

759 + 674, get 323 without considering carry.

If we only consider carrying, we get 1110.

So we get 759 + 674 = 323 + 1110 = 1433

What does the computer do with the binary number?

Use an exclusive or (^) without considering carry)

If we only consider the carry, we use (&) and shift left (<) at the same time.

Use recursion until the carry value is 0. Then the sum of the two numbers is obtained.

The following is the Java code:

   1: public int addNoArithm(int a, int b) {
   2:     if (b == 0) {
   3:         return a;
   4:     }
   5:     int sum = a ^ b;
   6:     int carry = (a & b) << 1;
   7:     return addNoArithm(sum, carry);
   8: }

PS: we do not need to use arithmetic operations to obtain the sum of two numbers. We should first think of bitwise operations, because it seems that we have no other choice.

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.