Java | Create an explicit addition function only using recursion and conditionals

前端 未结 2 1534
南笙
南笙 2021-01-23 18:30

Preface

By finding some free time in my schedule, I quested myself into improving my recursion skills (unfortunately). As practice, I want to recreate a

2条回答
  •  孤独总比滥情好
    2021-01-23 18:59

    public static int add(int a, int b) {
        if(b == 0) return a;
        int sum = a ^ b; //SUM of two integer is A XOR B
        int carry = (a & b) << 1;  //CARRY of two integer is A AND B
        return add(sum, carry);
    }
    

    Shamefully taken from here. All credit goes to its author.

提交回复
热议问题