- 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

# Previous number same as 1’s complement in C++

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

## Example

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

## Output

Both are the same

- 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
- Draw a Turing machine to find 1’s complement of a binary number
- C Program to find two’s complement for a given number
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- Count subarrays with equal number of 1’s and 0’s in C++
- Find One’s Complement of an Integer in C++
- Sort an arrays of 0’s, 1’s and 2’s using C++
- Find the number of integers from 1 to n which contains digits 0’s and 1’s only in C++
- Count the number of 1’s and 0’s in a binary array using STL in C++

Advertisements