Given a number check whether binary representation of its predecessor and its 1’s complement are same or not.
Input : 14
Output : NO
Storing 14 as a 4 bit number, 14 (1110), its predecessor 13 (1101), its 1’s complement 1 (0001), 13 and 1 are not same in their binary representation and hence output is NO.
Input : 8
Output : YES
Storing 8 as a 4 bit number, 8 (1000), its predecessor 7 (0111), its 1’s complement 7 (0111), both its predecessor and its 1’s complement are 7 and hence output is YES.
Simple Approach: In this approach, we actually calculate the complement of the number.
1. Find binary representation of the number’s predecessor and it’s 1’s complement using simple decimal to binary representation technique.
2. Compare bit by bit to check whether they are equal or not.
3. If all bits are equal then print YES else print NO.
Time Complexity: O (log n), as binary representation of numbers is getting calculated.
Auxiliary Space: O (1), although auxiliary space is O (1) still some memory spaces are getting
used to store binary representation of the numbers.
Efficient Approach: Only numbers which are powers of 2 have binary representation of their predecessor and their 1’s complement as same.
1. Check whether a number is power of 2 or not.
2. If a number is power of 2 then print YES else print NO.
// An efficient C++ program to check if binary
// representations of n’s predecessor and its
// 1’s complement are same.
#define ull unsigned long long int
using namespace std;
// Returns true if binary representations of
// n’s predecessor and it’s 1’s complement are same.
bool bit_check(ull n)
if ((n & (n – 1)) == 0)
ull n = 14;
cout << bit_check(n) << endl;
Time Complexity: O (1)
Auxiliary Space : O (1) No extra space is getting used.
- Complement of a number with any base b
- What’s difference between 1's Complement and 2's Complement?
- Program to Convert Octal Number to Binary Number
- DFA in LEX code which accepts even number of zeros and even number of ones
- Convert a binary number to hexadecimal number
- Prime number in PL/SQL
- Check if a number is Palindrome in PL/SQL
- log() function for complex number in C++
- Generate all the binary number from 0 to n
- Check whether the number has only first and last bits set | Set 2
- Program for nth Catalan Number
- Check if a number is in given base or not
- Sum of the digits of a number N written in all bases from 2 to N/2
- Check whether a number has consecutive 0's in the given base or not
- Lex Program to count number of words
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.