"Leetcode74" Sum of integers (without +,-for two numbers)

Source: Internet
Author: User

Title Description: No +,-for two numbers and the original description:

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.

Method one: Using the bitwise operation to simulate the addition idea 1:
    • It is also called "Modulo 2 Addition"
    • Set the variable recipe analog carry digit, simulate the implementation of the addition process
Code:
 Public classSolution { Public int Getsum(intAintb) {intR =0, C =0, recipe =1; while((a | b | c)! =0) {if((a ^ b ^ c) &1) !=0) r |= recipe; Recipe <<=1; c = (A & B | B & C | A & c) &1; A >>>=1; b >>>=1; }returnR }}
Method two: Different or evaluation thinking two:
    • A^b, get the results.
    • A&b, get the rounding.
    • Add
Code:
publicclass Solution {    publicintgetSum(intint b) {        while0) {            int//carry            //add             1;        }        return a;    }}
For more Leetcode classic algorithms, check out my Leetcode column with the following links:

Leetcode column

My QR code is as follows, welcome to exchange discussion

You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

"Leetcode74" Sum of integers (without +,-for two numbers)

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.