Adding and subtracting using bit arithmetic

Source: Internet
Author: User

I learned a bit about it today. Adding and subtracting with bitwise arithmetic because negative numbers are stored in a way that is complementary, the addition is realized by subtraction.

The addition operation is based on a theorem such as:

A + b = a^b + ((A & B) << 1)

It's good to go back to the point of rounding or zero.

Code:

1#include <iostream>2#include <cstdio>3#include <cstring>4 using namespacestd;5 6 int Get(intAintb) {7     intc = a ^b;8     intD = (A & B) <<1;9     if(c = =0|| D = =0) {Ten         returnB?D; One     } A     return Get(c, D); - } -  the intMain () { -     intA, B; -      while(EOF! = scanf ("%d%d", &a, &b)) { -printf"%d\n",Get(A, b)); +     } -     return 0; +}

Adding and subtracting using bit arithmetic

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.