[英]count number of digit using recursive method
Given a non-negative int n, compute recursively (no loops) the count of the occurrences of 8 as a digit, except that an 8 with another 8 immediately to its left counts double, so 8818 yields 4. Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12). 给定一个非负整数int n,则递归计算(无循环) ,将8的出现次数计数为一个数字,除了一个8紧随其后的另一个8计数为两倍,因此8818产生4。请注意,mod(%)除以10将产生最右边的数字(126%10为6),而除以(/)除以10将除去最右边的数字(126/10为12)。
count8(8) → 1
count8(818) → 2
count8(8818) → 4
my program seems not able to count double '8's. 我的程序似乎无法计算双'8'。 Here's the code.
这是代码。
public int count8(int n) {
boolean flag = false;
if(n<10)
{
if (n==8)
{
if(flag == true)
return 2;
else
{
flag = true;
return 1;
}
}
else
{
flag = false;
return 0;
}
}
else
return count8(n%10)+count8(n/10);
}
I was wondering if the last line goes wrong but I don't know how to check it. 我想知道最后一行是否出错,但是我不知道如何检查。 Looking forward to your help.
期待您的帮助。 Thanks!
谢谢!
Pass the state (is the previous digit eight ) to the method: 将状态 (前一位数字8 )传递给方法:
private static int count8(int n, boolean eight) {
if (n <= 0)
return 0;
else if (n % 10 == 8)
return 1 + (eight ? 1 : 0) + count8(n / 10, true);
else
return count8(n / 10, false);
}
public static int count8(int n) {
return count8(n, false);
}
Your flag variable is only local. 您的标志变量仅是本地的。 There's only one time you read it:
if (flag == true)
and since you never change it's value before that it will always be false. 您只有一次阅读它:
if (flag == true)
并且由于您在此之前从未更改过它的值,所以它永远是false。
You make this a lot more complicated than it has to be though. 您使它变得比必须的复杂得多。 No need for an additional parameter at all.
完全不需要额外的参数。
public int count8(int n)
{
if (n % 100 == 88) return count8(n/10) + 2;
if (n % 10 == 8) return count8(n/10) + 1;
if (n < 10) return 0;
return count8(n/10);
}
You can try smth like this: 您可以这样尝试:
public int count8(int n) {
if (n < 10)
return n == 8: 1 ? 0;
int count = 0;
String num = Integer.toString(n);
int numLength = num.length();
if (numLength % 2 != 0)
num += "0";
if ((num.charAt(numLength / 2) == num.charAt(numLength / 2 - 1)) && (num.charAt(numLength / 2) == "8"))
count++;
String left = num.substring(0, numLength / 2);
int leftInt = Integer.parseInt(left);
String rigth = num.substring(numLength / 2);
int rigthInt = Integer.parseInt(rigth);
return count + count8(leftInt) + count8(rigthInt);
}
C++ C ++
int count8(int n) {
return n == 0 ? 0 : (n % 10 == 8) + (n % 100 == 88) + count8(n/10);
}
Java & C# Java和C#
int count8(int n) {
if (n==0) return 0;
if(n % 100 == 88)
return 2 + count8(n / 10);
if(n % 10 == 8)
return 1 + count8(n / 10);
return count8(n / 10);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.