如何检查数字是否出现 3 次或更多次

How to check if digit appears 3 or more times in a long

我想验证一个长号。它必须是 12 位数字。如果它包含一个 0,或者任何数字出现 3 次或更多次,则该数字无效。我写了这段代码,如何检查任何数字是否出现了3次或更多次?

public boolean Valid(Long number) {
       
        String id = Long.toString(number);
        if(id.length() != 12)
            return false;
        if(String.valueOf(id).contains("0"))
            return false;

        //check if any digit appears 3 times or more        
        return false;
    }

Edit:: 刚刚意识到我误解了这里的要求,因为目标是考虑出现三次或更多次的任何数字。这是考虑到这一点的解决方案,以及一些更新的测试:

@Test
public void validationTest() {
    //12 chars, no digit repeated more than twice
    assertTrue(isValid(123456123456L));
    //Digit occurs three times
    assertFalse(isValid(123356123456L));
    //Digit occurs four times
    assertFalse(isValid(123336123456L));
    //Less than 12 length
    assertFalse(isValid(12L));
    //More than 12 length
    assertFalse(isValid(1234561234567L));
    //Contains 0
    assertFalse(isValid(103456123456L));
}

static boolean isValid(long in) {
    final String str = String.valueOf(in);

    if(str.length() != 12)
        return false;

    if(str.contains("0"))
        return false;

    return str.chars()
            .mapToObj(c -> (char)c)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .values().stream()
            .noneMatch(count -> count >= 3);
}

这是另一种更底层的方法,不使用流。有些人可能会觉得它更具可读性:

static boolean isValid(long in) {
    final String str = String.valueOf(in);

    if(str.length() != 12)
        return false;

    final int[] digits = new int[10];
    for(char c : str.toCharArray()) {
        final int idx = Character.getNumericValue(c);
        if(idx == 0 || ++digits[idx] >= 3)
            return false;
    }

    return true;
}

还有一个,因为我玩得很开心:

static boolean isValid(long in) {
    if((int)(Math.log10(in)+1) != 12)
        return false;

    final Map<Long, Long> map = LongStream.range(0,12)
            .map(i -> (in/(long)Math.pow(10,i))%10)
            .boxed()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    return !map.containsKey(0L) && map.values().stream().noneMatch(count -> count >= 3);
}

这可以有效地检测任何数字(输入您的字符串和 3)的出现。

static class IntPtr {
        int value;
}

static boolean hasRepetition(String s, int amount) {
        HashMap<Character, IntPtr> map = new HashMap<>();
        for(int i = 0; i < s.length(); i++) {
            IntPtr ip = map.computeIfAbsent(s.charAt(i), k -> new IntPtr());
            ip.value++;
            if(ip.value >= amount) {
                return true;
            }
        }
        return false;
    }

按数字分组并按计数检查

//return false if any digit appears 3 times or more
return id.chars().boxed()
  .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) // group by digit and get count
  .values().stream().noneMatch(count -> count >= 3); // filter by count >= 3

根据上面的检查,可以写出代码

  return id.length() == 12 
    && !id.contains("0") 
    && id.chars().boxed()
      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) // group by digit and get count
      .values().stream().noneMatch(count -> count >= 3);

免责声明

虽然流是有表现力的,但在复杂的情况下使用时会很难调试。

嗯,你可以扫描数字并数数:

public static boolean Valid(long number) {
  if (number < 1_000_000_000_000L || number >= 10_000_000_000_000L)
    return false;

  int[] digits = new int[10];

  for (long data = number; data != 0; data /= 10) {
    int digit = (int) (data % 10); 

    if (0 == digit)
      return false;   
    if (++digits[digit] >= 3)
      return false;
  } 

  return true; 
}

您可以使用一个数组来存储每个数字的出现次数,然后检查是否有任何数字出现超过 3 次,然后您可以 return false。

这是代码

 public class Main {
        public static boolean Valid(Long number) {
            int arr[]=new int[11];
            String id = Long.toString(number);
            if(id.length() != 12)return false;
            if(String.valueOf(id).contains("0"))
                return false;
            for(int i=0;i<id.length();i++){
                int temps =0;
                temps = id.charAt(i)-48;
                arr[temps]++;
            }
    
            for(int i=0;i<10;i++){
                if(arr[i]>=3)return false;
            }
    
            return true;
        }
        public static void main(String args[]) {
            System.out.println(Valid(103456789125L));  //false zero
            System.out.println(Valid(111456789125L)); //false 3
            System.out.println(Valid(125L)); //false less than 12 digits
            System.out.println(Valid(123456789123L)); //true 12 digits no zeros and not 3 digits repeted.
    
        }
    }

输出: