public static int countDigitx(int n, int x) {
int count = 0;
if (n == 0) {
count = 1;
} else if (n%10 == x) {
count++;
countDigitx(n+1,x);
}
return count;
}
我正在尝试但我觉得这不是我正在做的正确方法。 因为我认为我的逻辑在每个索引处找到数字是不正确的。例如,如果n = 23432且x = 4,那么输出应为1.
答案 0 :(得分:0)
你有三个非常糟糕的问题。
x
的情况下调用该方法。该调用不应该在else if
块内。n
,这将完全改变答案。你应该用10除以。答案 1 :(得分:0)
您使用的算法错误,这是您需要的更改:
public static int countDigitx(int n, int x) {
int count = 0;
if (n == 0) {
count = 0;
} else if (n%10 == x) {
count++;
count += countDigitx(n/10,x);
} else {
count += countDigitx(n/10,x);
}
return count;
}
原因:一旦检查数字的最后一位数字是否等于目标数字(x),您需要将数字除以10,这样您就可以检查下一位数字和等等等等。您还需要累积递归调用的计数。
答案 2 :(得分:0)
这是一个有效的递归解决方案,
public static int countDigitx(int n, int x) {
int count = 0;
String s = String.valueOf(n); // make n a String.
if (s != null && s.length() > 0) { // Check for not empty
String ch = String.valueOf(s.charAt(0)); // String valueOf 1st char
if (x == Integer.parseInt(ch)) { // Compare the int values
count++; // Add one to the count.
}
s = s.substring(1); // substring from 1.
if (s.length() > 0) {
count += countDigitx(Integer.parseInt(s), x); // add recursive result
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countDigitx(23432, 4)); // test
System.out.println(countDigitx(555, 5)); // test2
}
输出
1
3
答案 3 :(得分:0)
如果我理解正确的目标是计算数字' x'存在于您的号码中&n;#。您的递归通话countDigitx(n+1,x)
应为countDigitx(n/10,x)
。试着想一个更好的基础案例。想一想当您发送n = 1100
和x = 1
...
答案 4 :(得分:0)
我会修改函数,以便它采用字符串输入而不是int,更容易操作。如果你不能这样做,我会使用辅助函数(如图所示):
public static int countDigitx(int n, int x) { // this is the helper
return countDigitString(Integer.toString(n), Integer.toString(x));
}
public static int countDigitString(String n, String x){ // this is the recursive function
if (!n.contains(x))
return 0;
return (1 + countDigitString(n.substring(n.indexOf(x) , n.length()) , x)
}