LeetCode – Sum of Two Integers (Java)

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

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

Java Solution

Given two numbers a and b, a&b returns the number formed by '1' bits on a and b. When it is left shifted by 1 bit, it is the carry.

For example, given a=101 and b=111 (in binary), the a&b=101. a&b << 1 = 1010.

a^b is the number formed by different bits of a and b. a&b=10.

public int getSum(int a, int b) {
       int c = a&b;
   return a;
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • sai

    a– is a = a -1
    so you are still using + – operators

  • Ankit Shah

    if we could use operator ++ and — then following solution would work

    public static int sum(int a, int b) {
    while (b != 0) {
    if (b < 0) {
    } else {
    return a;