How to reverse digits of integer?

Another way would be

int digits = 12345;
StringBuilder buf = new StringBuilder(String.valueOf(digits));
System.out.println(buf.reverse());
System.out.println(Integer.valueOf(buf.toString()));

OK, here's a fun implementation with IntStream:

public static int reverse (int n) {
     return IntStream.iterate (n, i -> i/10) // produces a infinite IntStream of n, n/10, 
                                             // n/100, ...
                     .limit(10) // 10 elements are sufficient, since int has <= 10 digits
                     .filter (i -> i > 0) // remove any trailing 0 elements
                     .map(i -> i % 10) // produce an IntStream of the digits in reversed 
                                       // order
                     .reduce (0, (r,i) -> r*10 + i); // reduce the reversed digits back
                                                     // to an int
}

For example, for the input 123456789, it will first generate the infinite IntStream:

123456789,12345678,1234567,123456,12345,1234,123,12,1,0,0,...

After limiting to 10 elements and removing the 0s, we are left with:

123456789,12345678,1234567,123456,12345,1234,123,12,1

After mapping each element to its last digit, we get:

9,8,7,6,5,4,3,2,1

Now we just have to reduce the IntStream in a manner similar to what you did in your question - add each element to the intermediate result multiplied by 10:

((((0 * 10 + 9) * 10 + 8) * 10 + 7) * 10 ....) * 10 + 1

Note that if the input number has 10 digits and the last digit > 1, the reversed result will overflow.

It also doesn't support negative input.

Tags:

Java

Reverse