How to reverse a number in Java

Carvia Tech | September 07, 2019 | 1 min read | 90 views | Java Coding Challenges


Approach

  1. run a loop till num is greater than zero.

  2. extract last digit using modulus operator (digit = num % 10)

  3. add last digit with sum * 10 to make number reverse (sum = (sum * 10) + digit)

  4. divide num by to 10 so that we can get new last digit.

Reverse a number

Utils.java
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;
    }

}

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:
  1. Top 50 SDET Java Programming Interview Questions & Answers
  2. SDET: JUnit interview questions for automation engineer
  3. Write a program to reverse a string using recursion in Java
  4. Write a program to reverse the order of words in a string
  5. Check if the given number is Armstrong Number in Java
  6. How to check if the given number is palindrome in Java
  7. Check whether given number is even or odd



Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info