有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (4) 个答案

  1. # 1 楼答案

    你可以使用正则表达式:

    Pattern pattern = Pattern.compile("(0+)$");
    Matcher matcher = pattern.matcher(String.valueOf(123140000));
    Integer trailingZeroes = 0;
    if (matcher.find()) {
        trailingZeroes = matcher.group(1).length();
    } 
    System.out.println(trailingZeroes);
    
  2. # 2 楼答案

    下面是另一个使用Java 8流的解决方案:

    int trailingZeros = String.valueOf(number).chars()
            .reduce(0, (count, ch) -> (ch == '0') ? count + 1 : 0);
    

    这会将数字转换为IntStream。然后使用lambda减少该流,该lambda在每次出现非零字符时重置计数器

  3. # 3 楼答案

    如果它适合int/long,只需检查模10的数字是否为0,并保留一个计数器:

    long x = ...
    if (x == 0) {
        return 0;
    }
    int counter = 0;
    while (x % 10 == 0) {
        counter++;
        x /= 10;
    }
    

    如果它太大,无法放入long,请将其存储在String中,并从最后一个字符中计算零:

    String s = ...
    int counter = 0;
    while(counter < s.length() && s.charAt(s.length() - 1 - counter) == '0') {
        counter++;
    }
    
  4. # 4 楼答案

    可以将int转换为String并反向迭代,计算零,直到找到一个不是零的字符:

    int countZeros(int x){
        String a = Integer.toString(x);
        int numOfZeros = 0;
        for(int i = a.length() - 1; i >= 0; i--)
            if (a.charAt(i) != '0') break;
            else numOfZeros ++;
    
        return numOfZeros;          
    }
    

    使用测试:
    System.out.println(countZeros(25000));将打印3
    System.out.println(countZeros(25));将打印0

    希望这有帮助