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)