In: Computer Science
Doing recursion to match digits of two inputted integers. Found this online and it works but I wanna understand how each line works. Like why x %10 == y%10 and calling DigitMatch(x/10,y/10)?
public int digitMatch(int x, int y){
if(x < 0 || y < 0){
throw new IllegalArgumentException();
}
else if(x < 10 || y < 10){
if(x % 10 == y % 10)
return 1;
else
return 0;
} else if( x % 10 == y % 10){
return 1 + digitMatch(x/10, y/10);
}
else{
return digitMatch(x/10,y/10);
}
this program number of digits of two inputted int x and y
matches .
this program starts with left most digit of in x and y.
and keep traversing right(digit by digit) in each recursive
call.
if in any recursive call it found unmatch it return 0 .
else return 1(count increased by 1)
x%10 gives remainder when x is divided by 10
x/10 gives quotient when x is divided by 10
for example x=121 any y=221
call digitMatch(x/10,y/10) => digitMatch(121,221)
it starts with left most digit of x and y;
x%10 = 1
and y%10 = 1
and here (x%10==y%10)return 1
now we need to check whether next onward digits are same or
not
means now we will check
x/10 = 12
y/10 = 22
here we call recursively 1+ digitMatch(x/10,y/10) => 1+
digitMatch(12,22)
next call:
x%10 = 2
and y%10 = 2
and here (x%10==y%10)return 1
now we will check number of digits matched in
x/10 = 1
y/10 = 2
here we call recursively return 1+digitMatch(x/10,y/10) => 1+
digitMatch(1,2)
next call:
x%10 = 1
and y%10 = 2
and here (x%10!=y%10)return 0
here x <10 and y<10
return 0 (No more call)
total match = 1+1+0 = 2 digits matched