- 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 Complement vs 2's Complement
- 1's complement notation
- 1’s and 2’s complement of a Binary 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
- Design a Moore machine to generate 1's complement of a binary number.
- Draw a Turing machine to find 1’s complement of a binary number
- 10’s Complement of a decimal number?
- One’s Complement
- Two’s Complement
- 2's complement notation
- 2's complement fractions
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- C Program to find two’s complement for a given number
- Draw a Turing machine to find 2’s complement of a binary number

Advertisements