Posts

Showing posts from May, 2020

Add Two Numbers Without Arithmetic Operators 🙅‍♂️➕

Image
What if you are given a problem where you have to add two integers but you can't use any arithmetic operators ( + - * / % // ** ), like LeetCode's problem #371 . How do we approach this problem? Answer: Bit manipulation Problems like this can be solved using bit-wise operators as basic mathematics rules work in the same way whether it be binary or decimal. All we have to do is: Figure out how the basic mathematical operation works step by step. Replicate these operators using bit-wise operators ( & | ~ ^ << >> ). In case of addition in decimal system the process looks something like this: If sum of two digits is less than 10 we add it to our sum. If sum is greater than 10 then we add the least significant bit to sum and carry 1 to next operation. When doing this operation in binary which bit-wise operators do we need? Let's look at an example: 2 + 1 = 3 2 in binary is 010 1 in binary is 001 3 in binary is 011 Which b...