hi guys, i wrote a little recursive method that is supposed to reverse a number so that 123 will be 321. anyway it seems to only work half way. the method parameters are (number,number of digits) and each time it calls itself with new parameters like so -
sending:
(123,3)-->(23,2)-->(3,1)
returning:
3*10-->(30+2)*10-->320+1
(i need to somehow prevent if from multiplying by 10 at the last time)
here's the code:
PHP Code:
private static int reverse(int number, int numOfDigits) {
if (numOfDigits==1) {
System.out.println("Returning "+number*10);
return number*10;
}
//factor is used to divide a number like 312 to two numbers: 3 and 12
int factor=(int) Math.pow(10, numOfDigits-1);
// i've added these print commands for control
System.out.println("number is "+number+" digits "+numOfDigits);
System.out.println("Sending "+number%factor+" digits "+(numOfDigits-1));
System.out.println("Returning "+number/factor+reverse(number%factor,numOfDigits-1));
return number/factor+(reverse(number%factor,numOfDigits-1)*10);
}
public static void main(String[] args) {
int num=1234;
num=reverse(num,4);
System.out.println(num);
}
and the output, which is weird (it keeps going back and forth!):
PHP Code:
number is 1234 digits 4
Sending 234 digits 3
number is 234 digits 3
Sending 34 digits 2
number is 34 digits 2
Sending 4 digits 1
Returning 40
Returning 340
Returning 40
Returning 2403
number is 34 digits 2
Sending 4 digits 1
Returning 40
Returning 340
Returning 40
Returning 14032
number is 234 digits 3
Sending 34 digits 2
number is 34 digits 2
Sending 4 digits 1
Returning 40
Returning 340
Returning 40
Returning 2403
number is 34 digits 2
Sending 4 digits 1
Returning 40
Returning 340
Returning 40
40321
i hope i was clear enough, thanx for your help