How to perform multiplication, using bitwise operators?

前端 未结 7 1915
一个人的身影
一个人的身影 2020-12-04 13:28

I am working through a problem which i was able to solve, all but for the last piece - i am not sure how can one do multiplication using bitwise operators:

0         


        
7条回答
  •  旧时难觅i
    2020-12-04 14:07

    public static int multi(int x, int y){
            boolean neg = false;
            if(x < 0 && y >= 0){
                x = -x;
                neg = true;
            }
            else if(y < 0 && x >= 0){
                y = -y;
                neg = true;
            }else if( x < 0 && y < 0){
                x = -x;
                y = -y;
            }
    
            int res = 0;
            while(y!=0){
                if((y & 1) == 1) res += x;
                x <<= 1;
                y >>= 1;
            }
            return neg ? (-res) : res;
        }
    

提交回复
热议问题