
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Check If a Number Can Be Represented as Sum of Non-Zero Powers of 2 in C++
Here we will see, if we can represent a number as sum of two non-zero powers of 2. So we will check the given number N can be represented as (2x + 2y) where x, y > 0. Suppose a number is 10, this can be represented as 23 + 21.
The approach is simple. There are two cases. If the number n is even, it can be represented as 2x. Where x > 0. Another case is that is N is odd, it can never be represented as sum of powers of 2. We cannot use power as 0, so we cannot get odd numbers. for all odd numbers LSb of its binary representation is 1
Example
#include <iostream> using namespace std; bool isSumofTwosPower(int n) { if((n & 1) == 0){ return true; } else { return false; } } int main() { int num = 86; if(isSumofTwosPower(num)){ cout << "Can be represented"; } else { cout << "Cannot be represented"; } }
Output
Can be represented
Advertisements