My code below is suppose to take a DECIMAL number and print it backwards/reverse
ID: 3646945 • Letter: M
Question
My code below is suppose to take a DECIMAL number and print it backwards/reverse order. I am required to use recursion. Is the way I am doing it correct? Also, my code only works for numbers less than 10..any ideas on how to fix that?void reverseDigits(int number){
if(number >= 0) // Make sure we have a positive number
{
if(number < 10)
System.out.print(number);
else
{
System.out.print(number % 10); // This prints the right most number first (or in position 1)
reverseDigits(number / 10); // The remainder of the digits are to follow
}
}
}
Explanation / Answer
Ya thats good the reason it only works with digits less than 10 is because % actually just divides the number by 10 or whatever you put and gives you the remainder or fraction. For example you take 9 divide by 10 you get .9, so it returns 9. If you want to use numbers equal to or greater 10 then you have to divide by 100 and then numbers bigger than 999 by a thousand
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.