Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse digits of integer?

Tags:

java

reverse

public static int reverse(int n) {
    int result = 0;
    while (n > 0) {
        result = result * 10 + n % 10;
        n = n / 10;
    }
    return result;
}

I'm trying to reverse the digits of integer. Instead of doing the codes like what I have done, is there any other way to do it? Can i reverse it using java stream?

like image 758
Y.M Avatar asked Oct 12 '18 07:10

Y.M


People also ask

How do you reverse a 2 digit number?

There are two standard logics concerning two-digit numbers and their reverse. The general form of the two-digit number 'ab' is (10 \times a) + b. We know that to reverse a number, we should swap the numbers in TENS and ONES position. Therefore, the general form of its reverse 'ba' is (10 \times b) + a.

How do you reverse a 32-bit integer?

Given a signed 32-bit integer x , return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1] , then return 0 . Assume the environment does not allow you to store 64-bit integers (signed or unsigned).


2 Answers

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()));
like image 70
Scary Wombat Avatar answered Oct 19 '22 13:10

Scary Wombat


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.

like image 37
Eran Avatar answered Oct 19 '22 11:10

Eran