简体   繁体   English

查找两个数字之间的相似整数

[英]Find Similar Integers Between Two Numbers

There are two number variables.有两个数字变量。 I want to confirm and print similar integers between these two numbers.我想确认并打印这两个数字之间的相似整数。 Eg.例如。 Int num1 = 6229;整数 1 = 6229; int num2 = 2394. I want the program to print the shared integers of '2' and '9' and return 'true' for confirmation. int num2 = 2394。我希望程序打印“2”和“9”的共享整数并返回“true”进行确认。

public class Main {

    public static void main(String[] args) {
        System.out.println(hasSharedDigit(6229, 2394));
    }

    public static boolean hasSharedDigit(int firstNumber, int secondNumber) {

        int firstDigit;
        int secondDigit;

        while ((firstNumber > 0) && (firstNumber < 10000)) {
            firstDigit = firstNumber % 10;
            firstNumber /= 10;
            while ((secondNumber > 0) && (secondNumber < 10000)) {
                secondDigit = secondNumber % 10;
                secondNumber /= 10;
                if (!(firstDigit == secondDigit)) {
                    continue;
                }
                System.out.println(secondDigit);
                return true;
            }
        }
        return false;
    }
}

The DRY principle (Don't Repeat Yourself) guides you to move repeated code to a reusable helper method, so you should create a method that extracts the digits of a number into a Set , allowing you to easily use set intersection to find the digits they have in common. DRY 原则(Don't Repeat Yourself)指导您将重复的代码移动到可重用的辅助方法中,因此您应该创建一个将数字的数字提取到Set中的方法,让您可以轻松地使用集合交集来查找数字他们有共同点。

For this, aBitSet is the most appropriate "Set", so you could write the helper method like this:为此,BitSet是最合适的“Set”,因此您可以像这样编写辅助方法:

private static BitSet digitsOf(int number) {
    BitSet digits = new BitSet(10);
    do {
        digits.set(number % 10);
    } while ((number /= 10) != 0);
    return digits;
}

Now it's very easy to find shard digits of two numbers:现在很容易找到两个数字的分片数字:

public static boolean hasSharedDigit(int firstNumber, int secondNumber) {
    BitSet digits = digitsOf(firstNumber);
    digits.and(digitsOf(secondNumber));
    System.out.println(digits);
    return ! digits.isEmpty();
}

Test测试

System.out.println(hasSharedDigit(6229, 2394));
System.out.println(hasSharedDigit(0, 123));
System.out.println(hasSharedDigit(0, 404));

Output Output

{2, 9}
true
{}
false
{0}
true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM