Given an integer N, the task is to generate an N-digit number which is comprising only of digits 1 or 2 and is divisible by 2N.
Input: N = 4
Explanation: Since 2112 is divisible by 24 ( = 16).
Input: N = 15
Approach: Follow the steps below to solve the problem:
- Iterate over all values in the range [1, 2N].
- For each integer i in that range, generate its binary representation using bitset and store it in a string, say S.
- Reduce the length of the string S to N.
- Traverse the bits of S and if Si == ‘0’, set Si = ‘2’.
- Convert the obtained string to an integer, say res using stoll().
- If res is divisible by 2N, print the integer and break.
Below is the implementation of the above approach:
Time Complexity: O(2N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.