[Algorithm] 1. A+B Problem

Posted jjlovezz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Algorithm] 1. A+B Problem相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Algorithms - Strassen's algorithm for matrix multiplication 矩阵乘法 Strassen 算法

Algorithms - Strassen's algorithm for matrix multiplication 矩阵乘法 Strassen 算法

01Design and Analysis Algorithm Using Python-程振波

HDU 3374 String Proble

stl_algorithm算法之Max/Min算法

LeetCode Algorithm 1669. 合并两个链表