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

前端 未结 2 1538
南笙
南笙 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.

    0 讨论(0)
  • 2021-01-23 19:04
    public static int add (int a, int b) {
        if (b == 0) return a;
        if (b > a) return add (b, a);
        add (++a, --b);
    }
    

    Just with ++/--.

    0 讨论(0)
提交回复
热议问题