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++?
- Same Number Of Set Bits As N
- <bits/stdc++.h> in C++
- Find the node whose sum with X has minimum set bits
- Generate all the binary strings of N 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 1
- Complex numbers in C++ | Set 2
- C++ program to print all Even and Odd numbers from 1 to N
- Count numbers having 0 as a digit
- How will you print numbers from 1 to 100 without using loop?
- Converting Strings to Numbers in C/C++
- proj() function for Complex Numbers in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.