New*_*bie 6 java algorithm math division
我在接受采访时被问到以下问题,我不知道该怎么做
编写程序以找到可由0和9形成的最小数字,该数字可被给定数字整除.
例如,如果给定的数字是3输出应该是9,如果给定数字是2输出是90,如果给定数字是10输出是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;
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助您提供良好的理解或替代解决方案吗?
这是类似的方法。
我们如何手动执行 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.
Run Code Online (Sandbox Code Playgroud)
让我们看看这个模式。
0 9 90 99
Run Code Online (Sandbox Code Playgroud)
它看起来怎样?二进制!是的,我们有 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
Run Code Online (Sandbox Code Playgroud)
我们得到了所有可以用0和9按升序排列的数字。