我有一个练习,我必须编写一个接收整数和数字d的递归方法.此方法必须返回一个新数字,仅包含大于d的数字.
例如,对于数字19473和数字3,返回的数字将是947.
到目前为止,我的代码没有取得一些进展,所以我没有任何东西可以告诉你.方法的签名:
public static int filter(int n, int d)
Run Code Online (Sandbox Code Playgroud)
任何帮助都会很棒,
谢谢.
public static int filter(int n, int d)
{
if (n==0) return 0;
if (n%10>d) return 10*filter(n/10,d)+n%10;
else return filter(n/10,d);
}
Run Code Online (Sandbox Code Playgroud)
理解的关键:
整数n(n> 10),假设a = n/10 b = n%10.
你可以看到filter(n)=(String)filter(a)+(String)filter(b)(我的意思是,将结果转换为字符串并连接两个字符串.它在语法中无效,只是为了理解它) .
但是我们不需要弄脏String,算术会为整数做同样的工作.