首页 > 其他 > 详细

[Algorithm] 1. A+B Problem

时间:2018-11-02 18:29:06      阅读:115      评论:0      收藏:0      [点我收藏+]

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?

 

[Algorithm] 1. A+B Problem

原文:https://www.cnblogs.com/jjlovezz/p/9897625.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!