找到由给定数字整除的两位数字组成的最小数字

Find smallest number formed by two digits divisible by given number

我在面试中被问到以下问题,我不知道该怎么做

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

我在网上找到了这个解决方案,但我一点都不明白:-

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;
    }
}

任何人都可以帮助您更好地理解或提供替代解决方案吗?

我认为 translate 方法是需要更多说明的方法。 简单地说,它正在生成由“0”和“9”而不是“0”和“1”组成的 "bin" 数字的二进制表示。 "find" 方法从 1 开始检查 "translate" 生成的数字是否可以被 "divisible"

整除

这是一个类似的方法。

我们如何为 33 手动执行此操作:

Let's go from the least number which will be? - 0. Is it divisible? No.

Let's 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.

让我们看一下模式。

0 9 90 99

它看起来怎么样?二进制!是的,我们有 9 而不是 1。

现在我将从 0 开始,直到我得到一个以二进制形式除以它的数字(通过用 9 替换 1)。

我们得到

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

我们得到所有可以使用 0 和 9 以 升序.

组成的数字