Reputation: 79
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?
Upvotes: 7
Views: 6341
Reputation: 1143
the quickest answer will be :
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x%10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev*10+pop;
}
return rev;
}
Upvotes: 0
Reputation: 539
An easy way to reverse an integer is to parse it into a string, reverse it, and parse it back into a integer.
public static int reverse(int num) {
StringBuffer stringBuffer = new StringBuffer(String.valueOf(num););
stringBuffer.reverse();
return Integer.parseInt(stringBuffer.toString());
}
Upvotes: 1
Reputation: 2111
Along with the other answers, you can try this implementation as well.
public class MyStreamReverser {
public static void main(String[] args) {
streamApiReverser(-9008);
// other outputs to test:
// streamApiReverser(20000090);
// streamApiReverser(-04);
// streamApiReverser(39-02);
}
private static void streamApiReverser(int n) {
// produce an array of strings each having one digit
String[] stringArray = String.valueOf(n).split("\\B");
Stream<String> stringStream = Arrays.stream(stringArray);
stringStream.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(System.out::println);
}
}
Output:
8
0
0
-9
Note - Does not play well with leading zeros. 09
doesn't work (since those are treated as octals), works with trailing zeros, should be fine with negatives (but further testing needed).
Upvotes: 0
Reputation: 5193
A Stream
solution which returns for a given number the reversed String
:
int n = 10101010;
String reveresed = String.valueOf(n)
.chars()
.mapToObj(Character::getNumericValue)
.reduce("", (l, r) -> r + l, (l, r) -> l + r);
System.out.println(reveresed); // 01010101
If we convert the reversed String
to an Integer
and print it we will lose the leading zero:
System.out.println(Integer.valueOf(reveresed).toString()); // 1010101
Upvotes: 0
Reputation: 3955
One more stream and Math fun implementation.
public static long reverse(int n) {
return Stream.iterate(
Map.entry(0, n % 10),
entry -> Math.pow(10, entry.getKey()) <= n,
entry -> Map.entry(entry.getKey() + 1,
(int) (n % (int) Math.pow(10, entry.getKey() + 2) / Math.pow(10, entry.getKey() + 1))))
.map(Map.Entry::getValue)
.map(Integer::longValue)
.reduce(0L, (r, i) -> r * 10 + i);
}
You should return long in your method, anyway. But StringBuilder is the best here.
Upvotes: 0
Reputation: 394126
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.
Upvotes: 7
Reputation: 44854
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()));
Upvotes: 9