Sum of two numbers without using arithmetic operators Geeks For Geeks
Problem Link:
https://practice.geeksforgeeks.org/problems/sum-of-two-numbers-without-using-arithmetic-operators/1#
(It is also the problem of the day for 22-04-2022)
Solution:
class Solution
{
int sum(int a, int b)
{
return ((a|b)+(a&b));
}
}
Total Test Cases:310
Time Complexity: O(max number of bits(number 1, number 2))[As we will perform operations and for which we require all the bits.] [GFG Time:0.11/1.13]
Space Complexity: O(1)
Auxiliary Space: O(1)
Approach Used:
Here we will do two things.
1. Take or of two numbers
2. Take and of two numbers
eg if the number is 20 and the other is 40 then
20 = 10100 (5 bits) -> 010100 to convert it into 6 bits as another number is also 6 bits, so and operation will be performed easily and correctly.
40= 101000 (6 bits)
Now taking and of two numbers
and=010100 & 101000 -> 000000 ie 0
Now doing or operation we get
or=010100 | 101000 -> 111100 ie 60
Now and+or = 0+60 =60 =20+40
Hence we will get correct answer.
If we try to do it with a simple plus(+) operator then
class Solution
{
int sum(int a , int b)
{
return a+b;
//return ((a|b)+(a&b));
}
}
Time Complexity:O(1)[GFG Time:0.14/1.13]
Its time will be more than the previous approach because (+)works on numbers while the bitwise operators like & or | works on bits and bits are faster to compute in comparison with one single whole number.
It is the reason the time taken in the previous approach is less in comparison to this approach.
"Thanks For Reading.😇"
"Share Further To Increase Knowledge Treasure.😊"
Comments
Post a Comment