C + + does not implement integer addition with any arithmetic operator

Source: Internet
Author: User

This is a question of Careerup, see the future to do a bit, the main difficulty is the addition of the carry. Directly on the code:

1 intAddintAintb)2 {3     Const intBitsize =sizeof(int) *8;4     intDigit[bitsize] = {0};5     intFirst = A, second =b;6     intcarry =0;7     intresult =0;8      for(inti =0; i < bitsize; i++)9     {Ten          OneDigit[i] = (First &1) ^ (Second &1) ^carry; A  -         if((First &1) ==1&& (Second &1) ==1) || (First &1) ==1&& carry = =1) || (Carry = =1&& (Second &1) ==1)) -carry =1; the         Else -carry =0; -  -First = First >>1; +Second = Second >>1; -  +result = Result | (Digit[i] <<i); A     } at     returnresult; -      -}

Later on the web found a more convenient method:

1 intAdd_no_arithm (intAintb)2 {3     if(b = =0)returnA;4     intsum = a ^ b;//add without carrying5     intCarry = (A & B) <<1;//carry, but don ' t add6     returnAdd_no_arithm (sum, carry);//recurse7}

It's ingenious, carry is the place to carry.

C + + does not implement integer addition with any arithmetic operator

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.