查找 2 个给定整数中位数之间差异的递归方法
Recursive method that finds the difference between the number of digits in 2 given ints
输入是两个给定的整数,都是N个数,输出必须是差的结果。例如,对于第一个数字是 1234,第二个数字是 1,输出必须是 3。我尝试编写一个递归方法,但它不让我减去它们,说需要两个整数但找到了一个。
这是到目前为止的代码:
public static int digitDiffer (int a, int b){
int sumA = 0;
int sumB = 0;
if(a == 0 && b==0){
return 0;
}
else {
sumA += a % 10;
a /= 10;
sumB += b % 10;
b /= 10;
}
return digitDiffer (sumA-sumB);
}
这是我的方法
public static int digitDiffer (int a, int b){
// I will divide a and b by 10 until one of them is 0
if(a != 0 && b != 0) return digitDiffer(a/10, b/10);
//if b == 0 and a != 0 then I will count how many times I can divide a by 10 until it becomes 0
if(a != 0 && b == 0) return 1 + digitDiffer(a/10, 0);
// if a == 0 and b != 0 then I will count how many times I can divide b by 10 until it becomes 0
if(a == 0 && b != 0) return 1 + digitDiffer(0, b/10);
return 0;
}
输出示例:对于 a = 12345
和 b=1
,输出将是:4
输入是两个给定的整数,都是N个数,输出必须是差的结果。例如,对于第一个数字是 1234,第二个数字是 1,输出必须是 3。我尝试编写一个递归方法,但它不让我减去它们,说需要两个整数但找到了一个。 这是到目前为止的代码:
public static int digitDiffer (int a, int b){
int sumA = 0;
int sumB = 0;
if(a == 0 && b==0){
return 0;
}
else {
sumA += a % 10;
a /= 10;
sumB += b % 10;
b /= 10;
}
return digitDiffer (sumA-sumB);
}
这是我的方法
public static int digitDiffer (int a, int b){
// I will divide a and b by 10 until one of them is 0
if(a != 0 && b != 0) return digitDiffer(a/10, b/10);
//if b == 0 and a != 0 then I will count how many times I can divide a by 10 until it becomes 0
if(a != 0 && b == 0) return 1 + digitDiffer(a/10, 0);
// if a == 0 and b != 0 then I will count how many times I can divide b by 10 until it becomes 0
if(a == 0 && b != 0) return 1 + digitDiffer(0, b/10);
return 0;
}
输出示例:对于 a = 12345
和 b=1
,输出将是:4