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

 Live Demo

#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

Updated on: 03-Feb-2020

213 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements