- 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

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.

#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); }

One's Complement of 22 is: 9

- Related Questions & Answers
- One’s Complement
- Two’s Complement
- Check if one of the numbers is one’s complement of the other in Python
- 1’s and 2’s complement of a Binary Number?
- 10’s Complement of a decimal number?
- C Program to find two’s complement for a given number
- Previous number same as 1’s complement in C++
- 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
- Sort an arrays of 0’s, 1’s and 2’s using C++
- 1's Complement vs 2's Complement
- Find the Pattern of 1’s inside 0’s using C++
- Complement of Base 10 Integer in Python
- Find longest sequence of 1’s in binary representation with one flip in C++
- Find yesterday’s, today’s and tomorrow’s date in Python

Advertisements