- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Find One’s Complement of an Integer in C++

In this section, we will see how to find the 1’s complete of an integer. We can use the complement operator to do this task very fast, but it will make 32bit complemented value (4-bype integer). Here we want complement of n bit numbers.

Suppose we have a number say 22. The binary equivalent is 10110. The complemented value is 01001 which is same as 9. Now the question comes, how to find this value? At first we have to find number of bits of the given number. Suppose the count is c (here c = 5 for 22). We have to make 5 1s. So this will be 11111. To make this, we will shift 1 to the left c number of times, then subtract 1 from it. After shifting 1 to the left 5 times, it will be 100000, then subtract 1, so it will be 11111. After that perform XOR operation with the 11111 and 10110 to get the complement.

## Example

#include <iostream> #include <cmath> using namespace std; int findComplement(int n) { int bit_count = floor(log2(n))+1; int ones = ((1 << bit_count) - 1); return ones ^ n; } int main() { int number = 22; cout << "One's Complement of " << number << " is: " << findComplement(number); }

## Output

One's Complement of 22 is: 9

- Related Questions & Answers
- One’s Complement
- 1's Complement vs 2's Complement
- Complement of Base 10 Integer in Python
- Check if one of the numbers is one’s complement of the other in Python
- Two’s Complement
- 1's complement notation
- 2's complement notation
- 2's complement fractions
- 10’s Complement of a decimal number?
- 8085 program to find 1's and 2's complement of 8-bit number
- 8085 program to find 1's and 2's complement of 16-bit number
- 8085 program to find 2's complement of the contents of Flag Register
- 1’s and 2’s complement of a Binary Number?
- Draw a Turing machine to find 1’s complement of a binary number
- Draw a Turing machine to find 2’s complement of a binary number