- Related Questions & Answers
- 1’s and 2’s complement of a Binary Number?
- One’s Complement
- Two’s Complement
- 1's Complement vs 2's Complement
- 10’s Complement of a decimal number?
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- 1's complement notation
- Find One’s Complement of an Integer in C++
- Find the number of integers from 1 to n which contains digits 0’s and 1’s only in C++
- 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
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Maximum length of segments of 0’s and 1’s in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- Maximum 0’s between two immediate 1’s in binary representation in C++

- 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 problem, we are given an integer n. Our task is to check weather the preceding number is equal to 1’s complement of the number.

Let’s take a few examples to understand our problem

Input: 12 Output: No Explanation: (12)10 = (1100)_{2}Preceding number 11 = (1011)_{2}1’s complement of 12 = (0011)_{2}Input: 4 Output: Yes Explanation: 4 = (100)_{2}Preceding number 3 = (011)_{2}1’s complement of 12 = (011)_{2}

To solve this problem, we can use a simple approach which is by comparing the previous number and the 1’s complement of the number.

This approach is simple but consumes space and time. time complexity: O(n)

An effective solution could be using the general method that we seek to solve the problem. Here, only the number which are powers of 2 will satisfy the condition i.e. the previous number is equal to 1’s complement.

Program to show the implementation of our solution

#include <iostream> using namespace std; bool sameBits(unsigned long int n){ if ((n & (n - 1)) == 0) return true; return false; } int main(){ unsigned long int n = 64; if(sameBits(n)) cout<<"Both are the same"; else cout<<"Both aren't the same"; return 0; }

Both are the same

Advertisements