java—一种递归方法,用于查找两个给定整数的位数之间的差异

9jyewag0  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(225)

输入是两个给定的整数,都是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);
 }
bprjcwpo

bprjcwpo1#

这是我的方法

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;
    }

输出示例:for a = 12345 以及 b=1 输出为: 4

相关问题