Given two unsigned integers (maximum possible input can be of 32 bits). The task is to add two numbers using bit operations.
Input: n1 = 12, n2 = 34 Output: 46 Input: n1 = 12564 n2 = -1 Output: 12563
Approach: Since we know that in bit addition
- 1+1=0 carry 1
- if(carry==1) 1+1=1 carry 1
Represent integer using bitset function in C++ . It behaves like an array which stores the LSB (Least Significant Bit) at 0th index and when we print such an array it prints the binary representation in reverse format. Add every bit from right according to the bits addition property and store in the third bitset. Function to_ulong() is used to convert a bitset form into its decimal form.
Below is the implementation of the above approach.
- What happens if loop till Maximum of Signed and Unsigned in C/C++?
- <bits/stdc++.h> in C++
- Same Number Of Set Bits As N
- Generate all the binary strings of N bits
- Find the node whose sum with X has minimum set bits
- Find a number containing N - 1 set bits at even positions from the right
- Count number of set bits in a range using bitset
- How to count set bits in a floating point number in C?
- Complex numbers in C++ | Set 2
- Complex numbers in C++ | Set 1
- How will you print numbers from 1 to 100 without using loop?
- Converting Strings to Numbers in C/C++
- Count numbers having 0 as a digit
- proj() function for Complex Numbers in C++
- Modulus of two float or double numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.