Find the smallest number consisting of two digits divisible by a given number

In an interview, they asked me the following question, and I had no idea how to do this

Write a program to find the smallest number that can be formed 0 and 9, which is divided by a given number.
For example, if a number is given - 3 outputs should be 9, if the given number is 2 outputs - 90, if the given number is 10, then it is 90

I found this solution online, but I did not understand this one: -

public class Smallest0And9DivisibleNumber { public static int find(int divisible) { int bin = 1; while (true) { int res = translate(bin); if (res % divisible == 0) { return res; } bin += 1; } } private static int translate(int bin) { int result = 0; for (int i = Integer.toBinaryString(bin).length(); i > 0; i--) { result *= result != 0 ? 10 : 0; int mask = 1 << (i - 1); result += (bin & mask) == mask ? 9 : 0; } return result; } public static void main(String[] args) { assert find(10) == 90; assert find(99) == 99; assert find(33) == 99; assert find(3) == 9; assert find(333) == 999; assert find(300) == 900; assert find(303) == 909; assert find(3033) == 9099; assert find(3303) == 9909; } } 

Can anyone help with a good understanding or alternative solution?

+6
source share
2 answers

This is a similar approach.

How to do it manually for 33:

 Let go from the least number which will be? - 0. Is it divisible? No. Let go up a number. 9. Is it divisible? No. Again by a number 90. Is is divisible? No. Again by a number 99. Is it divisible? Yes. 

Look at the template.

 0 9 90 99 

What does it look like? binary! Yes, instead of 1 we have 9.

Now I will go from 0 until I get the number that divides it as binary code (by replacing 1 with 9).

we get

 Number Binary 0 And 9 0 0 0 1 1 9 2 10 90 3 11 99 4 100 900 5 101 909 6 110 990 7 111 999 

We get all the numbers that can be formed using 0 and 9 in ascending order .

+2
source

I guess the translation method is one that needs more explanation. It just generates a binary representation of the number "bin" consisting of "0" and "9" instead of "0" and "1". Although the "find" method starts with 1 and checks if the number generated by "translate" is divisible by "divisible"

0
source

Source: https://habr.com/ru/post/988990/


All Articles