[英]Recursive method that finds the difference between the number of digits in 2 given ints
輸入是兩個給定的整數,都是 N 個數字,output 必須是差異的結果。 例如,對於第一個數字是 1234,第二個是 1,output 必須是 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;
}
Output 示例:對於a = 12345
和b=1
,output 將為: 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.