Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use +
or any arithmetic operators.)
My Answer
Using a recursion method to solve this problem!
- 1 /**
- 2 * @param a: An integer
- 3 * @param b: An integer
- 4 * @return: The sum of a and b
- 5 */
- 6 int aplusb(int a, int b) {
- 7 // Recursion process
- 8 if ( (a & b) == 0 ){
- 9 return a ^ b;
- 10 } else {
- 11 return aplusb( (a^b), ((a&b)<<1) );
- 12 }
- 13 }
Tips
It's not the only way to get the right answer. Can you try the other way like the loop structure?