Power of Two Difference

Power of Two Difference

Power of Two Difference

Problem Description

Given an integer n, return true if it is a possible difference between powers of two. Otherwise, return false.

An integer n is a difference between powers of two if there exist two integers x and y, where x >= y >= 0, such that n == 2^x - 2^y.

Solution Approach

The problem can be solved using an elegant solution. We can observe that if n = 2^x - 2^y, then n = 2^y * (2^(x-y) - 1). Let's call y as M and x - y as N. Now, we observe that 2^N - 1 is a binary number of the form 111...111, where 1 is repeated N times. Multiplying a binary number by 2^M will add 0 M times to the right. Therefore, our result is of the form 11...1100...00, where 1 is repeated some times followed by 0 repeated some times or 0 times. For example, 0 is true, 7 is true because it's 111, 12 is true because it's 1100, whereas 5 is false because it's 101 and 13 is false because it's 1101.

To solve the problem, we need to find the binary expansion of N and check if it's of the form 11...1100...000.

Playground Link

You can access the playground link that includes the solution code.

Example Test Cases

Test Case 1:

Input:
n = 0

Output:
true

Explanation:
0 = 2^0 - 2^0

Test Case 2:

Input:
n = 12

Output:
true

Explanation:
12 = 2^4 - 2^2

Test Case 3:

Input:
n = 7

Output:
true

Explanation:
7 = 2^3 - 2^0

Test Case 4:

Input:
n = 5

Output:
false

Explanation:
It is not possible to represent 5 as a difference of powers of 2.

Tags

Math, Bit Manipulation

Comments

Popular posts from this blog

Encrypt and Decrypt Strings

Degree of an Array

Minimum Sum of Four Digit Number After Splitting Digits