easy to understand C# bit-wise add


  • 0
    Y
    public class Solution {
        public int GetSum(int a, int b) {
            if (a == 0) return b;
        	if (b == 0) return a;
            int carry=0,res=0;
        	for(int i=0;i<32;i++)
        	{
        	    int sum=(a&1)+(b&1)+carry;
        	    if(sum>1)
        	        {carry=1;
        	        sum=sum-2;}
        	    else
        	        {carry=0;}
        	    res |= (sum<<i);
        	    a = a>>1;
        	    b = b>>1;
        	}
        	return res;
        }
    }

  • 1
    I

    you are using the + operator though


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.