当前位置: 移动技术网 > IT编程>开发语言>C/C++ > [Algorithm] 1. A+B Problem

[Algorithm] 1. A+B Problem

2018年11月03日  | 移动技术网IT编程  | 我要评论

抗日奇侠 下载,金钱之味快播,环保意识

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?

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网