-
Notifications
You must be signed in to change notification settings - Fork 17
/
ReverseDigitsOrder.java
42 lines (36 loc) · 1009 Bytes
/
ReverseDigitsOrder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package by.andd3dfx.numeric;
/**
* <pre>
* Revert order of digits in Integer number:
* 0 -> 0
* 12389 -> 98321,
* 123490 -> 94321,
* -123 -> -321
* </pre>
*
* @see <a href="https://youtu.be/w3C4L7GxD7M">Video solution</a>
*/
public class ReverseDigitsOrder {
public static int usingString(int number) {
var isNegative = false;
if (number < 0) {
isNegative = true;
number = -number;
}
var string = String.valueOf(number);
var reversedString = new StringBuilder(string).reverse().toString();
if (isNegative) {
reversedString = "-" + reversedString;
}
return Integer.valueOf(reversedString);
}
public static int usingNumber(int number) {
int result = 0;
do {
int digit = number % 10;
result = result * 10 + digit;
number /= 10;
} while (number != 0);
return result;
}
}