欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[Algorithm] 1. A+B Problem

程序员文章站 2023-01-28 15:38:04
Description Description Write a function that add two numbers A and B. Clarification Are a and b both 32-bit integers? Yes. Can I use bit operation? S ......

description

write a function that add two numbers a and b.

clarification

are a and b both 32-bit integers?

  • yes.

can i use bit operation?

  • sure you can.

example

given a=1 and b=2 return 3.

challenge

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?