如何用Java计算整数中的尾随零? (例如:234000 => 3个零)

标题几乎是自我解释的。 🙂

1232 => 0 1231030 => 1 2000 => 3 34444400000 => 5 

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

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

它太大而不适合long ,将它存储在String并从最后一个char计数零:

 String s = ... counter = 0; while(counter < s.length() && s.charAt(s.length() - 1 - counter) == '0') { counter++; } 

你总是可以使用正则表达式:

 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); 

三行:

 int zeroes = 0 while(num%10 == 0 && num != 0) { zeroes++; num /= 10; } 

这使用模数运算符。 只要我们可以在没有余数的情况下除以10,就增加计数器。

以下是使用Java 8 Streams的另一种解决方案:

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

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

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

 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

希望这可以帮助。

没试过这个代码,但这应该工作。

 int counterForZeros=0; for(long i=10;true;) { if(num%i==0) { counterForZeros++; i*=10; } else { break; } } System.out.println("Number of zeros in "+num+" is "+counterForZeros); 

好吧,如果这是一场比赛,看谁能在最少的线上做到这一点:

 trailingZeroes = String.valueOf(num).length() - String.valueOf(num).replaceAll("0*$","").length();