Just share my java bitwise operations


  • 1
    A

    public class Solution {

    public int getSum0(int a,  int b){
        return getBitwiseSum0(a, b);
    }
    
    public int getSum(int a,  int b){
        return getBitwiseSubtract0(a, negate(b));
    }
    
    public int getSubtract0(int a, int b){
        return b==0? a : getBitwiseSum0(a, negate(b));
    }
    
    public int getSubtract(int a, int b){
        return b==0? a : getBitwiseSubtract0(a, b);
    }
    
    public int getBitwiseSum0(int a, int b) {
        while(b!=0){
            int c = a & b;
            a = a ^ b;
            b = c << 1;
        }
        return a;
    }
    
    public int getBitwiseSum1(int a, int b){
        return b==0? a : getSum(a ^ b, (a & b)<<1);
    }
    
    
    /*
        X 	Y     Diff  Borrow
        0 	0 	  0 	0
        0 	1 	  1 	1
        1 	0 	  1 	0
        1 	1 	  0 	0
    **/
    public int getBitwiseSubtract0(int a, int b){
        while(b != 0){
            int borrow = ~a & b;
            a = a ^ b;
            b = borrow << 1;
        }
        
        return a ;
    }
    
    public int getBitwiseSubtract1(int a, int b){
        return b==0? a : getBitwiseSubtract1(a ^ b, (~a & b)<<1);
    }
    
    
    public int negate(int a){
        int mask = -1;
        int carry = 1;
        int inv = ~a;
        while((carry & inv) != 0){
            carry <<= 1;
            mask <<= 1;
            inv &= mask;
        }
        return inv | carry;
    }
    

    }


Log in to reply
 

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