---
# System prepended metadata

title: Untitled

---

- 所挑選的題目
    Sum of Two Integers

- //1. java

    
    class Solution {
    public int getSum(int a, int b) {
        while (b != 0) {
            int sum = a ^ b;
            int carry = (a & b) << 1;
            a = sum;
            b = carry;
        }
        return a;
    }
}

- //2.c++

class Solution {
public:
    int getSum(int a, int b) {
        int bitoR = a | b;
        int bitanD = a & b ;
        int carry = 0;
        int sum = 0;
        for(int i = 0 ; i < 32 ; i ++)
        {
          if((bitanD &( 1<<i)) && carry == 1)
          {
            sum = (sum | (1<<i));
            carry = 1;
          }
          else if((bitanD &( 1<<i)))
          {
              carry = 1;            
          }
          else if((bitoR &( 1<<i)) && carry == 1)
          {
              carry = 1;
          }
          else if((bitoR &( 1<<i))){
              sum = (sum | (1<<i));
              carry = 0;
          }
          else{
            sum = (sum | (carry<<i));
            carry = 0;
          }
        }
      return sum;
    }
};

- //3.c
    int getSum(int a, int b){
    unsigned int sum = (unsigned int)a ^ (unsigned int)b;
    unsigned int carry = ((unsigned int)a & (unsigned int)b) << 1;
    while(carry != 0)
    {
        unsigned int temp = sum ^ carry;
        carry = (sum & carry) << 1;
        sum = temp;
    }
    return (int)sum;
}

- //4.JavaScript
    var getSum = function(a, b) {
    while(b) {
        let carry = (a & b) << 1;
        a ^= b;
        b = carry;
    }
    return a;
};
