public class Utils {
public static long reverse(long num) {
long sum = 0;
while (num != 0) {
long lastDigit = (num % 10);
sum = (sum * 10) + lastDigit;
num = num / 10;
}
return sum;
}
}
How to reverse a number in Java
Upasana | September 07, 2019 | 1 min read | 1,108 views | Java Coding Challenges
Approach
-
run a loop till
num
is greater than zero. -
extract last digit using modulus operator (
digit = num % 10
) -
add last digit with
sum * 10
to make number reverse (sum = (sum * 10) + digit
) -
divide num by to
10
so that we can get new last digit.
Reverse a number
Utils.java
Junit test for program
We can quickly write Junit Testcase to test our method for various scenarios, here we will cover only basic ones in one testcase.
UtilsTest,java
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.*;
public class UtilsTest {
@Test
public void reverse() {
assertThat(Utils.reverse(201), equalTo(102L));
assertThat(Utils.reverse(100), equalTo(1L));
assertThat(Utils.reverse(1), equalTo(1L));
assertThat(Utils.reverse(1564654), equalTo(4564651L));
}
}
Top articles in this category:
- Reverse a string using recursion in Java
- Java Coding Problems for SDET Automation Engineer
- Java Program to find Factorial of a number
- Reverse order of words inside string in Java
- Armstrong Number in Java
- Check whether given number is even or odd
- Reverse position of words in a string using recursion
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..