Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
2年前关闭。
我正在写一种计算给定数字阶乘中尾随零的数量的方法。
例如:
6! = 720-> 1后退零
12! = 479001600-> 2个尾随零
这是我的代码
它的工作正常。但是我认为这不是一种有效的算法。请帮忙,谢谢。
Demo
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
2年前关闭。
我正在写一种计算给定数字阶乘中尾随零的数量的方法。
例如:
6! = 720-> 1后退零
12! = 479001600-> 2个尾随零
这是我的代码
import java.math.BigInteger;
public class TrailingZeros
{
public static void main(String[] args)
{
int n = 12;
System.out.println(solution(n));
}
public static int solution(int n)
{
// computing factorial
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
{
result = result.multiply(new BigInteger(i + ""));
}
String str = String.valueOf(result);
int count = 0;
char[] chars = str.toCharArray();
// counting numbers of trailing zeros
for (int i = chars.length - 1; i >= 0; i--)
{
if (chars[i] != '0')
break;
count++;
}
return count;
}
}
它的工作正常。但是我认为这不是一种有效的算法。请帮忙,谢谢。
最佳答案
我认为您当前的方法本身没有任何问题。但是我们实际上可以使用单线计数尾随零,将原始数字字符串的长度与去除尾随零的数字的长度进行比较:
String input = "479001600";
int numZeroes = input.length() - input.replaceAll("0+$", "").length();
System.out.println(numZeroes);
2
Demo
关于java - N的尾随零数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51094838/
10-12 06:08