简体   繁体   English

在两个数字中寻找共享数字的麻烦

[英]Troubles with looking for shared digits in two numbers

I need to check whether two numbers have some shared digits. 我需要检查两个数字是否有一些共享数字。 My method here doesn't return anything when tested. 我的方法在测试时不返回任何内容。

What I'm trying to do here is to get each digit of the first number, then loop through the second number to try finding another digit that is equal to the first one. 我在这里想要做的是获取第一个数字的每个数字,然后遍历第二个数字以尝试查找与第一个数字相等的另一个数字。 If so, I want to return true and if not I want to keep checking. 如果是这样,我想返回true,否则,我要继续检查。

    public static boolean hasSharedDigit(int num1, int num2) {
        int digit1, digit2;
        boolean isShared;
        boolean isNum1TwoDigits = ((num1 >= 10) && (num1 <= 99)) ? true : false;
        boolean isNum2TwoDigits = ((num2 >= 10) && (num2 <= 99)) ? true : false;
        if ((!isNum1TwoDigits) || (!isNum2TwoDigits))
            return false;
        while (num1 > 10) {
            digit1 = num1 % 10;
             while (num2 > 10) {
                digit2 = num2 % 10;
                if (digit2 == digit1)
                    return true;
             }
             num1 /= 10;
        }
        return false;

    }

Probably not the most efficient method, but you could create a Set containing the digits of which each number is composed and then check that the intersection is not empty. 可能不是最有效的方法,但是您可以创建一个Set ,该Set包含由每个数字组成的数字,然后检查交集是否为空。

public static Set<Integer> getDigits(int num)
{
  Set<Integer> result = new TreeSet<Integer>();

  if (num == 0)
    result.add(0);
  else
  {
    num = Math.abs(num);
    while (num > 0)
    {
      result.add(num % 10);
      num /= 10;
    }
  }

  return (result);

} // getDigits

public static boolean hasSharedDigit(int num1, int num2)
{
  Set<Integer> digits1 = getDigits(num1);
  Set<Integer> digits2 = getDigits(num2);
  digits1.retainAll(digits2);
  return (!digits1.isEmpty());
}

Here is a basic solution that converts the numbers to arrays of characters and compares them in two for loops 这是将数字转换为字符数组并在两个for循环中进行比较的基本解决方案

public static boolean hasSharedDigit(int num1, int num2) {
    if (num1 == num2) {
        return true;
    }

    char[] arr1 = String.valueOf(num1).toCharArray();
    char[] arr2 = String.valueOf(num2).toCharArray();

    for (char ch1 : arr1) {
        for (char ch2 : arr2) {
            if (ch1 == ch2) {
                return true;
            }
        }
    }
    return false;
}

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

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