计数代码中出现的零个数

时间:2019-11-12 19:07:28

标签: java if-statement recursion

我的代码在读取的文本文件中计数了错误的零,我不确定如何解决它。随机数比我需要的多一个或根本不读。有人可以帮忙吗?

private static int count0(int n, boolean zero) {
  if (n <= 0)
    return 0;
  else if (n % 10 == 0)
    return 1 + (zero ? 1 : 0) + count0(n / 10, true);
  else
    return count0(n / 10, false);
}

public static int count0(int n) {
  return count0(n, false);
}

enter code here

1 个答案:

答案 0 :(得分:1)

摆脱“零”,我们有

  

n为0->计数为0
  否则,如果此数字为零,则加1,然后
  计算左边的零位数

private static int count0(int n) {
  if (n <= 0)
    return 0;
  else 
    return  (n % 10 == 0 ? 1 :0) + count0(n / 10);
}

这适用于(例如)原始n = 10,但IMO不适用于原始n = 0;答案一定是1?也就是说,0是特例。 '10'和'0'都有一个零。