Not asking for code, but I'm wondering if anyone can give me some advice and pointers for writing a code that reverses an inputted int, without using the string reverse.

5 Years
Discussion Span
Last Post by NexG

As an integer. So for example if I input 5432, then it would reverse it and output 2345.


If the digits were written on pieces of paper and you wanted to reverse them, how would you do it?
Take the input's right most digit and move it to the output area, shifting the digits that were already there in the output area one position to the left and appending the new digit on the right end.
Shift the input's remaining digits to the right.
Loop back and do it again.

Edited by NormR1: n/a


Hint :

Start the loop 
Divide the number with 10 until it becomes single digit number
Get the last digit everytime by modulus operator
Append the next last digit of number and iterate the loop till num becomes single digit

Depends on how you want to do with the value afterward.

If you want to keep the value for later use, you could keep it as int and do as harinath_2007 suggested.

If you just want to display the result only, you can convert the int to String (using Integer.toString(int_value)) and then display the string in reverse.

Edited by Taywin: n/a


So here are my results:

import java.util.Scanner;
public class reverse{
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter Number: ");
		int number = scanner.nextInt();//the entered number is an integer
		int reversedNumber = 0;
		int temp = 0;
		while(number > 0)//shifting the digits over by using %10 && *10
			temp = number%10;
			reversedNumber = reversedNumber * 10 + temp;
			number = number/10;
		System.out.print("Reversed Number is: " + reversedNumber);
		System.out.println(" ");

It works great :) Thanks to everyone who contributed!

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.