File tree Expand file tree Collapse file tree 2 files changed +55
-21
lines changed
main/java/com/thealgorithms/maths
test/java/com/thealgorithms/maths Expand file tree Collapse file tree 2 files changed +55
-21
lines changed Original file line number Diff line number Diff line change 11package com .thealgorithms .maths ;
22
3- import java .lang .IllegalStateException ;
4- import java .util .NoSuchElementException ;
5- import java .util .Scanner ;
3+ import java .lang .IllegalArgumentException ;
64
7- public class ReverseNumber {
8-
9- public static void main (String [] args ) {
10- int number ;
11- int reverse = 0 ;
5+ /**
6+ * @brief utility class reversing numbers
7+ */
8+ final public class ReverseNumber {
9+ private ReverseNumber () {
10+ }
1211
13- try (Scanner sc = new Scanner (System .in )) {
14- System .out .println ("Enter a number:" );
15- number = sc .nextInt ();
16- } catch (NoSuchElementException | IllegalStateException e ) {
17- System .out .println ("ERROR: Invalid input" );
18- return ;
12+ /**
13+ * @brief reverses the input number
14+ * @param number the input number
15+ * @exception IllegalArgumentException number is negative
16+ * @return the number created by reversing the order of digits of the input number
17+ */
18+ public static int reverseNumber (int number ) {
19+ if (number < 0 ) {
20+ throw new IllegalArgumentException ("number must be nonnegative." );
1921 }
2022
21- while ( number ! = 0 ) {
22- int remainder = number % 10 ;
23-
24- reverse = reverse * 10 + remainder ;
25- number = number / 10 ;
23+ int result = 0 ;
24+ while ( number > 0 ) {
25+ result *= 10 ;
26+ result += number % 10 ;
27+ number /= 10 ;
2628 }
27-
28- System .out .println ("The reverse of the given number is: " + reverse );
29+ return result ;
2930 }
3031}
Original file line number Diff line number Diff line change 1+ package com .thealgorithms .maths ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4+ import static org .junit .jupiter .api .Assertions .assertThrows ;
5+
6+ import java .util .HashMap ;
7+
8+ import org .junit .jupiter .api .Test ;
9+
10+ public class ReverseNumberTest {
11+
12+ @ Test
13+ public void testReverseNumber () {
14+ HashMap <Integer , Integer > testCases = new HashMap <>();
15+ testCases .put (0 , 0 );
16+ testCases .put (1 , 1 );
17+ testCases .put (10 , 1 );
18+ testCases .put (123 , 321 );
19+ testCases .put (7890 , 987 );
20+
21+ for (final var tc : testCases .entrySet ()) {
22+ assertEquals (ReverseNumber .reverseNumber (tc .getKey ()), tc .getValue ());
23+ }
24+ }
25+
26+ @ Test
27+ public void testReverseNumberThrowsExceptionForNegativeInput () {
28+ assertThrows (
29+ IllegalArgumentException .class ,
30+ () -> ReverseNumber .reverseNumber (-1 )
31+ );
32+ }
33+ }
You can’t perform that action at this time.
0 commit comments