[java] Java reverse an int value without using array

Can anyone explain to me how to reverse an integer without using array or String. I got this code from online, but not really understand why + input % 10 and divide again.

while (input != 0) {
    reversedNum = reversedNum * 10 + input % 10;
    input = input / 10;   
}

And how to do use this sample code to reverse only odd number. Example I got this input 12345, then it will reverse the odd number to output 531.

This question is related to java integer reverse

The answer is


public static int reverse(int x) {
    boolean negetive = false;
    if (x < 0) {
        x = Math.abs(x);
        negative = true;
    }

    int y = 0, i = 0;
    while (x > 0) {
        if (i > 0) {
            y *= 10;
        }

        y += x % 10;
        x = x / 10;
        i++;
    }
    return negative ? -y : y;
}

If the idea is not to use arrays or string, reversing an integer has to be done by reading the digits of a number from the end one at a time. Below explanation is provided in detail to help the novice.

pseudocode :

  1. lets start with reversed_number = 0 and some value for original_number which needs to be reversed.
  2. the_last_digit = original_number % 10 (i.e, the reminder after dividing by 10)
  3. original_number = original_number/10 (since we already have the last digit, remove the last digit from the original_number)
  4. reversed_number = reversed_number * 10 + last_digit (multiply the reversed_number with 10, so as to add the last_digit to it)
  5. repeat steps 2 to 4, till the original_number becomes 0. When original_number = 0, reversed_number would have the reverse of the original_number.

More info on step 4: If you are provided with a digit at a time, and asked to append it at the end of a number, how would you do it - by moving the original number one place to the left so as to accommodate the new digit. If number 23 has to become 234, you multiply 23 with 10 and then add 4.

234 = 23x10 + 4;

Code:

public static int reverseInt(int original_number) {
        int reversed_number = 0;
        while (original_number > 0) {
            int last_digit = original_number % 10;
            original_number = original_number / 10;
            reversed_number = reversed_number * 10 + last_digit;    
        }
        return reversed_number;
    }

while (num != 0) {
    rev = rev * 10 + num % 10;
    num /= 10;
}

That is the solution I used for this problem, and it works fine. More details:

num % 10

This statement will get you the last digit from the original number.

num /= 10

This statement will eliminate the last digit from the original number, and hence we are sure that while loop will terminate.

rev = rev * 10 + num % 10

Here rev*10 will shift the value by left and then add the last digit from the original.
If the original number was 1258, and in the middle of the run time we have rev = 85, num = 12 so:
num%10 = 2
rev*10 = 850
rev*10 + num%10 = 852


See to get the last digit of any number we divide it by 10 so we either achieve zero or a digit which is placed on last and when we do this continuously we get the whole number as an integer reversed.

    int number=8989,last_num,sum=0;
    while(number>0){
    last_num=number%10; // this will give 8989%10=9
    number/=10;     // now we have 9 in last and now num/ by 10= 898
    sum=sum*10+last_number; //  sum=0*10+9=9;
    }
    // last_num=9.   number= 898. sum=9
    // last_num=8.   number =89.  sum=9*10+8= 98
   // last_num=9.   number=8.    sum=98*10+9=989
   // last_num=8.   number=0.    sum=989*10+8=9898
  // hence completed
   System.out.println("Reverse is"+sum);

Just to add on, in the hope to make the solution more complete.

The logic by @sheki already gave the correct way of reversing an integer in Java. If you assume the input you use and the result you get always fall within the range [-2147483648, 2147483647], you should be safe to use the codes by @sheki. Otherwise, it'll be a good practice to catch the exception.

Java 8 introduced the methods addExact, subtractExact, multiplyExact and toIntExact. These methods will throw ArithmeticException upon overflow. Therefore, you can use the below implementation to implement a clean and a bit safer method to reverse an integer. Generally we can use the mentioned methods to do mathematical calculation and explicitly handle overflow issue, which is always recommended if there's a possibility of overflow in the actual usage.

public int reverse(int x) {
    int result = 0;

    while (x != 0){
        try {
            result = Math.multiplyExact(result, 10);
            result = Math.addExact(result, x % 10);
            x /= 10;
        } catch (ArithmeticException e) {
            result = 0; // Exception handling
            break;
        }
    }

    return result;
}

int convert (int n)
{
        long val = 0;

        if(n==0)
            return 0;

        for(int i = 1; n > exponent(10,  (i-1)); i++)
        {
            int mod = n%( (exponent(10, i))) ;
            int index = mod / (exponent(10, i-1));

            val *= 10;
            val += index;
        }

        if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE) 
        {
            throw new IllegalArgumentException
                (val + " cannot be cast to int without changing its value.");
        }
        return (int) val;

    }


static int exponent(int m, int n)
    {
        if(n < 0) 
            return 0;
        if(0 == n) 
            return 1;

        return (m * exponent(m, n-1));

    }

Simply you can use this

    public int getReverseInt(int value) {
        int resultNumber = 0;
        for (int i = value; i !=0; i /= 10) {
            resultNumber = resultNumber * 10 + i % 10;
        }
        return resultNumber;        
    }

You can use this method with the given value which you want revers.


public static int reverse(int x) {
    int tmp = x;
    int oct = 0;
    int res = 0;
    while (true) {
        oct = tmp % 10;
        tmp = tmp / 10;
        res = (res+oct)*10;
        if ((tmp/10) == 0) {
            res = res+tmp;
            return res;
        }
    }
}

public static void reverse(int number) {
    while (number != 0) {
        int remainder = number % 10;
        System.out.print(remainder);
        number = number / 10;
    }

    System.out.println();
}

What this does is, strip the last digit (within the 10s place) and add it to the front and then divides the number by 10, removing the last digit.


Even if negative integer is passed then it will give the negative integer Try This...

public int reverse(int result) {

    long newNum=0,old=result;
    result=(result>0) ? result:(0-result);

    while(result!=0){
        newNum*=10;
        newNum+=result%10;
        result/=10;
        if(newNum>Integer.MAX_VALUE||newNum<Integer.MIN_VALUE)
            return 0;
    }
    if(old > 0)
        return (int)newNum;
    else if(old < 0)
        return (int)(newNum*-1);
    else 
        return 0;
}

while (input != 0) {
  reversedNum = reversedNum * 10 + input % 10;
  input = input / 10;
}

let a number be 168,
+ input % 10 returns last digit as reminder i.e. 8 but next time it should return 6,hence number must be reduced to 16 from 168, as divide 168 by 10 that results to 16 instead of 16.8 as variable input is supposed to be integer type in the above program.


It is an outdated question, but as a reference for others First of all reversedNum must be initialized to 0;

input%10 is used to get the last digit from input

input/10 is used to get rid of the last digit from input, which you have added to the reversedNum

Let's say input was 135

135 % 10 is 5 Since reversed number was initialized to 0 now reversedNum will be 5

Then we get rid of 5 by dividing 135 by 10

Now input will be just 13

Your code loops through these steps until all digits are added to the reversed number or in other words untill input becomes 0.


public int getReverseNumber(int number)
{
    int reminder = 0, result = 0;
    while (number !=0)
    {
        if (number >= 10 || number <= -10)
        {
            reminder = number % 10;
            result = result + reminder;
            result = result * 10;
            number = number / 10;
        }
        else
        {
            result = result + number;
            number /= 10;
        }
    }
    return result;

}

// The above code will work for negative numbers also


If you wanna reverse any number like 1234 and you want to revers this number to let it looks like 4321. First of all, initialize 3 variables int org ; int reverse = 0; and int reminder ; then put your logic like

    Scanner input = new Scanner (System.in);
    System.out.println("Enter number to reverse ");
    int org = input.nextInt();
    int getReminder;
    int r = 0;
    int count = 0;

    while (org !=0){
        getReminder = org%10;
         r = 10 * r + getReminder;
         org = org/10;



    }
        System.out.println(r);

    }

It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.

if((inputNum <= 999999999)&&(inputNum > 0 ))
{
   System.out.print("Your number reversed is: ");

   do
   {
      endInt = inputNum % 10; //to get the last digit of the number
      inputNum /= 10;
      system.out.print(endInt);
   }
   While(inputNum != 0);
 System.out.println("");

}
 else
   System.out.println("You used an incorrect number of integers.\n");

System.out.println("Program end");

This is the shortest code to reverse an integer

int i=5263; 
System.out.println(Integer.parseInt(new StringBuffer(String.valueOf(i) ).reverse().toString()));

import java.util.Scanner;

public class Reverse_order_integer {
    private static Scanner scan;

    public static void main(String[] args) {
        System.out.println("\t\t\tEnter Number which you want to reverse.\n");
        scan = new Scanner(System.in);
        int number = scan.nextInt();
        int rev_number = reverse(number);
        System.out.println("\t\t\tYour reverse Number is = \"" + rev_number
                           + "\".\n");
    }

    private static int reverse(int number) {
        int backup = number;
        int count = 0;
        while (number != 0) {
            number = number / 10;
            count++;
        }
        number = backup;
        int sum = 0;
        for (int i = count; i > 0; i--) {
            int sum10 = 1;
            int last = number % 10;
            for (int j = 1; j < i; j++) {
                sum10 = sum10 * 10;
            }
            sum = sum + (last * sum10);
            number = number / 10;
        }
        return sum;
    }
}

123 maps to 321, which can be calculated as 3*(10^2)+2*(10^1)+1 Two functions are used to calculate (10^N). The first function calculates the value of N. The second function calculates the value for ten to power N.

Function<Integer, Integer> powerN = x -> Double.valueOf(Math.log10(x)).intValue();
Function<Integer, Integer> ten2powerN = y -> Double.valueOf(Math.pow(10, y)).intValue();

// 123 => 321= 3*10^2 + 2*10 + 1
public int reverse(int number) {
    if (number < 10) {
        return number;
    } else {
        return (number % 10) * powerN.andThen(ten2powerN).apply(number) + reverse(number / 10);
    }
}

import java.util.Scanner;

public class ReverseOfInteger {
    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        int x = input.nextInt();
        System.out.print(helpermethod(x));
    }

    public static String helpermethod(int x) {
        if (x == 0)
            return "";
        String a = String.valueOf(x % 10);
        return a + helpermethod(x / 10);

    }
}

A method to get the greatest power of ten smaller or equal to an integer: (in recursion)

public static int powerOfTen(int n) {
    if ( n < 10)
        return 1;
    else
        return 10 * powerOfTen(n/10); 
}

The method to reverse the actual integer:(in recursion)

public static int reverseInteger(int i) {
    if (i / 10 < 1)
        return i ;
    else
        return i%10*powerOfTen(i) + reverseInteger(i/10);
}

    Scanner input = new Scanner(System.in);
        System.out.print("Enter number  :");
        int num = input.nextInt(); 
        System.out.print("Reverse number   :");
        int value;
        while( num > 0){
            value = num % 10;
            num  /=  10;
            System.out.print(value);  //value = Reverse
            
             }

public static void main(String args[]) {
    int n = 0, res = 0, n1 = 0, rev = 0;
    int sum = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please Enter No.: ");
    n1 = scan.nextInt(); // String s1=String.valueOf(n1);
    int len = (n1 == 0) ? 1 : (int) Math.log10(n1) + 1;
    while (n1 > 0) {
        rev = res * ((int) Math.pow(10, len));
        res = n1 % 10;
        n1 = n1 / 10;
        // sum+=res; //sum=sum+res;
        sum += rev;
        len--;
    }
    // System.out.println("sum No: " + sum);
    System.out.println("sum No: " + (sum + res));
}

This will return reverse of integer


I used String and I converted initially the int to String.Then I used the reverse method. I found the reverse of the number in String and then I converted the string back to int. Here is the program.

import java.util.*;

public class Panathinaikos {
    public static void my_try()
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number you want to be reversed");
        int number = input.nextInt();
        String sReverse = Integer.toString(number);
        String reverse = new StringBuffer(sReverse).reverse().toString();
        int Reversed = Integer.parseInt(reverse);
        System.out.print("The number " + number+ " reversed is " + Reversed);
    }
}

You can use recursion to solve this.

first get the length of an integer number by using following recursive function.

int Length(int num,int count){
    if(num==0){
        return count;
    }
    else{
        count++;
        return Lenght(num/10,count);
    }
}

and then you can simply multiply remainder of a number by 10^(Length of integer - 1).

int ReturnReverse(int num,int Length,int reverse){
    if(Length!=0){
        reverse = reverse + ((num%10) * (int)(Math.pow(10,Length-1)));
        return ReturnReverse(num/10,Length-1,reverse);
    }
    return reverse;
}

The whole Source Code :

import java.util.Scanner;

public class ReverseNumbers {

    int Length(int num, int count) {
        if (num == 0) {
            return count;
        } else {
            return Length(num / 10, count + 1);
        }
    }

    int ReturnReverse(int num, int Length, int reverse) {
        if (Length != 0) {
            reverse = reverse + ((num % 10) * (int) (Math.pow(10, Length - 1)));
            return ReturnReverse(num / 10, Length - 1, reverse);
        }
        return reverse;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int N = scanner.nextInt();

        ReverseNumbers reverseNumbers = new ReverseNumbers();
        reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), 0));

        scanner.close();
    }
}

 public static int reverseInt(int i) {
    int reservedInt = 0;

    try{
        String s = String.valueOf(i);
        String reversed = reverseWithStringBuilder(s);
        reservedInt = Integer.parseInt(reversed);

    }catch (NumberFormatException e){
        System.out.println("exception caught was " + e.getMessage());
    }
    return reservedInt;
}

public static String reverseWithStringBuilder(String str) {
    System.out.println(str);
    StringBuilder sb = new StringBuilder(str);
    StringBuilder reversed = sb.reverse();
    return reversed.toString();
}

Java reverse an int value - Principles

  1. Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4

  2. Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50

  3. Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7

Java reverse an int value - Pseudocode:

a. Extract off the rightmost digit of your input number. (1234 % 10) = 4

b. Take that digit (4) and add it into a new reversedNum.

c. Multiply reversedNum by 10 (4 * 10) = 40, this exposes a zero to the right of your (4).

d. Divide the input by 10, (removing the rightmost digit). (1234 / 10) = 123

e. Repeat at step a with 123

Java reverse an int value - Working code

public int reverseInt(int input) {
    long reversedNum = 0;
    long input_long = input;

    while (input_long != 0) {
        reversedNum = reversedNum * 10 + input_long % 10;
        input_long = input_long / 10;
    }

    if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) {
        throw new IllegalArgumentException();
    }
    return (int) reversedNum;
}

You will never do anything like this in the real work-world. However, the process by which you use to solve it without help is what separates people who can solve problems from the ones who want to, but can't unless they are spoon fed by nice people on the blogoblags.


int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());

Reversing integer

  int n, reverse = 0;
  Scanner in = new Scanner(System.in);
  n = in.nextInt();

  while(n != 0)
  {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
  }

  System.out.println("Reverse of the number is " + reverse);

Here is a complete solution(returns 0 if number is overflown):

public int reverse(int x) {
    boolean flag = false;

    // Helpful to check if int is within range of "int"
    long num = x;

    // if the number is negative then turn the flag on.
    if(x < 0) {
        flag = true;
        num = 0 - num;
    }

    // used for the result.
    long result = 0;

    // continue dividing till number is greater than 0
    while(num > 0) {
        result = result*10 + num%10;
        num= num/10;
    }

    if(flag) {
        result = 0 - result;
    }

    if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
        return 0;
    }
    return (int) result;
}

public static double reverse(int num)
{
    double num1 = num;
    double ret = 0;
    double counter = 0;

    while (num1 > 1)
    {   
        counter++;
        num1 = num1/10;
    }
    while(counter >= 0)
    {
        int lastdigit = num%10;
        ret += Math.pow(10, counter-1) * lastdigit;
        num = num/10;
        counter--;  
    }
    return ret;
}

Java solution without the loop. Faster response.

int numberToReverse;//your number 
StringBuilder sb=new StringBuilder();
sb.append(numberToReverse);
sb=sb.reverse();
String intermediateString=sb.toString();
int reversedNumber=Integer.parseInt(intermediateString);

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class intreverse
{
public static void main(String...a)throws Exception
{
    int no;
    int rev = 0;
    System.out.println("Enter The no to be reversed");
    InputStreamReader str=new InputStreamReader(System.in);
    BufferedReader br =new BufferedReader(str);
    no=Integer.parseInt(br.readLine().toString());
    while(no!=0)
    {
        rev=rev*10+no%10;
        no=no/10;

    }
    System.out.println(rev);
}
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to reverse

Right way to reverse a pandas DataFrame? Reverse Contents in Array Reverse a string without using reversed() or [::-1]? angular ng-repeat in reverse Reversing an Array in Java Reversing a String with Recursion in Java Print a list in reverse order with range()? How to reverse an std::string? Python list sort in descending order How to get a reversed list view on a list in Java?