2021-12-01_学习不用算数运算符求解A+B问题

备注:题目备注了取值范围:a和b以及a+b,都大于负的2的31次方,小于2的31次方减1(这是Java中int的取值范围,即a+b不会溢出)。

1. ^异或 是位运算符的一种。位运算符应用于long、int、short、byte、char。

2. 0异或0得0,0异或1得1,1异或0得1,1异或1得0。基于此,异或运算有了个别名:不进位加法。

3. 学习 https://blog.csdn.net/qq_32534441/article/details/89255605 后,敲其代码:

public class Solution {
    public static int aplusb(int a, int b) {
        int s = a ^ b; // s为结果
        int t = a & b; // t为进位

        while (t != 0) {
            int tempA = s;
            int tempB = t << 1;
            s = tempA ^ tempB;
            t = tempA & tempB;
        }

        return s;
    }
}

 

posted on 2021-12-02 07:09  平凡力量  阅读(59)  评论(0编辑  收藏  举报