Smallest number whose digits multiplication is ‘N’

You are given a positive integer ‘N’. The task is to find and return the smallest number, ‘M’, such that the multiplication of all the digits in ‘M’ is equal to ‘N’. If no such ‘M’ is possible or ‘M’ cannot fit in a 32-bit signed integer, return 0.

Example:
‘N’ = 90

Possible values for ‘M’ are:
1. 259 (2*5*9 = 90) 
2. 3352 (3*3*5*2 = 90) 
3. 2335 (2*3*3*5 = 90) 
4. 952 (9*5*2 = 90), and so on.
Here, ‘259’ is the smallest possible ‘M’. Thus, you should return ‘259’ as the answer.
Input format:
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.

The first and only line of each test case contains an integer ‘N’, i.e., the given integer.
Output format:
For every test case, return the smallest possible ‘M’ value. If no such ‘M’ is possible or ‘M’ cannot fit in a 32-bit signed integer, return 0.
Note:
You do not need to print anything; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 1000
1 <= N <= 10^9

Time limit: 1 sec
CodingNinjas
author
2y
Brute force

A simple approach will be to iterate through all possible ‘M’ values, i.e., from ‘1’ to ‘2147483647’ (the largest value that a signed 32-bit integer field can hold), and check if their digi...read more

CodingNinjas
author
2y
Greedy approach

The smallest value of ‘M’ must satisfy the following two conditions:

  • The number of digits in ‘M’ must be minimum. To achieve this, assign the maximum possible number of 9’s to ‘M’ (keep ...read more
Help your peers!
Add answer anonymously...
TCS Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter