[Algorithm] 1. A+B Problem

2018-11-03 08:49:49来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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?

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:级数求和(C++)

下一篇:C++操作MYSQL遇到的一些问题