Leetcode 371. Sum of integers

Source: Internet
Author: User

371. Sum of integers
    • Total accepted:10773
    • Total submissions:20732
    • Difficulty:easy

Calculate the sum of of the integers a and b, but is not allowed to use the operator + and - .

Example:

Given a = 1 and b = 2, return 3.

Idea: Using binary bit operations to achieve number addition. Just find the carry, add it to the XOR result.

With the action & filter out the bits that can be rounded, and then move those bits 1 bits to the left, equal to the carry, Xor ^ can filter out the bits without rounding.

For the binary operation principle, you can refer to the bits operation.

Code:

Iteration:

1 classSolution {2  Public:3     intGetsum (intAintb) {4         intcarry;5          while(b) {6carry= (a&b) <<1;7A=a^b;8b=carry;9         }Ten         returnA; One     } A};

Recursion:

1 class Solution {2 public:3     int getsum (int a, int b) {4         if (!b) return a;5         return Getsum (A^b, (a&b) <& LT;1); 6     }7};

There are also subtraction and inverse numbers in the int range without the + and-implementation:

1 //iterative2  Public intGetsubtract (intAintb) {3      while(b! =0) {4         intBorrow = (~a) &b;5A = a ^b;6b = Borrow <<1;7     }8     9     returnA;Ten } One  A //Recursive -  Public intGetsubtract (intAintb) { -     return(b = =0) ? A:getsubtract (a ^ B, (~a & B) <<1); the } -  - //Get Negative number -  Public intNegateintx) { +     return~x +1; -}

Leetcode 371. Sum of integers

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.