Java implements addition, subtraction, multiplication and division through bit operations

Addition, subtraction, multiplication, and division by bit operations ±*/

First of all, pay attention: the principle we all know-(Note: There has been a theorem since ancient times: subtraction can be obtained by addition, and division can be obtained by multiplication;
)

A brief analysis of the process of addition

/**
     * 加法
     * @param ja
     * @param jb
     * @return
     */
    private static int add(int ja, int jb){
    
    
        int tempJ;
        while ((tempJ = ((ja & jb ) << 1)) != 0){
    
    
            ja = ja ^ jb;
            jb = tempJ;
        }
        return ja ^ jb;
    }

subtraction process

	/**
     * 减法
     * @param a
     * @param b
     * @return
     */
    private static int desic(int a, int b){
    
    
        return add(a, add(~b, 1));
    }

multiplication process

	/**
     * 乘法
     * @param a
     * @param b
     * @return
     */
    private static int cheng(int a,int b){
    
    
        int c = 0;
        while (a != 0){
    
    
            if((a & 1) == 1){
    
    
                c = add(c, b);
            }
            b <<= 1;
            a >>= 1;
        }
        return c;
    }

Analysis of division process

	/**
     * 除法操作
     * @param a
     * @param b
     * @return
     */
    private static int devide(int a,int b){
    
    
        if(b == 0){
    
    
            System.out.println("除数不能为0!");
            return -1;
        }
        int x = a < 0 ? -a : a;
        int y = b < 0 ? -b : b;
        int end = 0;
        for (int i = 31; i >= 0 ; i = desic(i,1)) {
    
    
            if(y <= (x >> i)){
    
    
                end = add(end, (1 << i));
                x = desic(x, y << i);
            }
        }
        return end;
    }

Note: Brothers, pay attention to overflow because it is of type int

Guess you like

Origin blog.csdn.net/weixin_43795840/article/details/121829108