# 4.8 Reverse Digits

#1

Hello there,
I’m going over EPI in Java. (This is my first question, so wanted to say big thanks to putting this wonderful book together to the authors )

For problem 4.8, reverse digits, is there a particular reason why we want to use the absolute value of the input and apply the sign at the end?

If we have a negative number as an input, modulo of negative number will also be negative, and negative number * 10 is also a negative, so it all seems to work out nicely without having to drop the sign and apply it back at the end. The code below passed the epi judge. Is there something that I am missing?

``````long reversedX = 0;
while ( x != 0 ) {
reversedX = reversedX * 10 + ( x % 10 );
x /= 10;
}
return reversedX;``````

#2

Hi @shong,

Easiest way to verify that is using http://epijudge.com/. Please go ahead to test that and let us know.

#3

hello @tsunghsienlee , yep, this code has passed the epi judge. I was pretty sure the above code was functional but I was also wondering if there was any subtle reason that I couldn’t think of!

#4

Hi @shong,

Many thanks for the suggestion, and one of the reason is that our solution is consistent with the one in Python where shifting a negative number won’t never result to 0. However, in C++ and Java, it is definitely possible to use this idea here.

Again, really appreciate for your idea, and please keep doing that!