- Related Questions & Answers
- Add minimum number to an array so that the sum becomes even in C programming
- C++ Program for Dijkstra’s shortest path algorithm?
- C/C++ Program for nth Catalan Number?
- C Program to Check if all digits of a number divide it
- Concatenate a string given number of times in C++ programming
- Ways to paint N paintings such that adjacent paintings don’t have same colors in C programming
- Superperfect Number in C programming
- HTML DOM Input Number value Property
- HTML DOM Input Number type Property
- How to find the number of days in a month of a particular year in Java?
- Number of elements a particular tag contains in JavaScript?
- Print multiples of Unit Digit of Given Number in C Program
- C/C++ Programming to Count trailing zeroes in factorial of a number?
- C++ Programming for Smallest K digit number divisible by X?
- To find sum of even factors of a number in C++ Program?

- 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