天天看點

使用純粹的ABAP位操作實作兩個整數相加

Recently I came across this very funny picture and I would like to share with you.

This picture shows totally five different approaches to implement “a + b”, and how your brain reacts when you read these code

From this picture we know that for most guys, they will be crazy when they read the source code of the last solution as the code is really difficult to understand compared with all other four solutions.

使用純粹的ABAP位操作實作兩個整數相加

The idea of the last solution is to achieve the add operation via bitwise operation &, | and ^. See detail of these three operations via wikipedia.

You might be interested with how ABAP can play around with these bitwise operation from two of my blogs:

Bitwise operation ( OR, AND, XOR ) on ABAP Integer

An interview question: Compare two integers without +,-,*,/ or > and <

Back to the last solution to implement a + b using bitwise operation, the code actually conveys the idea how the Adder is designed in electronics. See detail design in Wikipedia.

使用純粹的ABAP位操作實作兩個整數相加

The idea is to use & to determine whether there is a carry about the add result of current bit, and use | to store the add result of current bit.

For example, how 2 + 3 = 5 works via bitwise operation:

使用純粹的ABAP位操作實作兩個整數相加

And here below is my implementation using ABAP( Only integers which >= 0 are supported ).

使用純粹的ABAP位操作實作兩個整數相加
使用純粹的ABAP位操作實作兩個整數相加

This solution might not make too much sense from business perspective but it at least help me refresh what I have learned in my university.

繼續閱讀