371. Sum of Two Integers (实现二进制全加器)

╰半夏微凉° 2022-07-15 01:37 231阅读 0赞

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

Example:

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

  1. public class Solution {
  2. public int getSum(int a, int b) {
  3. int temp=1,prev=0,tempA,tempB,tempRes,result = 0;
  4. for(int i=0;i<32;i++){
  5. tempA = a&temp;
  6. tempB = b&temp;
  7. tempRes = tempA^tempB^prev;
  8. prev = ((tempA^tempB)&prev|tempA&tempB)<<1;
  9. result |= tempRes;
  10. temp<<=1;
  11. }
  12. return result;
  13. }
  14. }

发表评论

表情:
评论列表 (有 0 条评论,231人围观)

还没有评论,来说两句吧...

相关阅读