Java reverse an int value without using array
Asked Answered
V

34

44

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.

Vowelize answered 27/9, 2010 at 17:13 Comment(0)
N
35

I am not clear about your Odd number. The way this code works is (it is not a Java specific algorithm) Eg. input =2345 first time in the while loop rev=5 input=234 second time rev=5*10+4=54 input=23 third time rev=54*10+3 input=2 fourth time rev=543*10+2 input=0

So the reversed number is 5432. If you just want only the odd numbers in the reversed number then. The code is:

while (input != 0) {    
    last_digit = input % 10;
    if (last_digit % 2 != 0) {     
        reversedNum = reversedNum * 10 + last_digit;

    }
    input = input / 10; 
}
Nord answered 27/9, 2010 at 17:21 Comment(6)
theres a mistake in your code. It should be reversedNum = reversedNum * 10 + input % 10;Goddart
Now it is proper I assume. The input=input/10 will take care and there will be no infinite loop.Nord
if the input is 1534236469 then what is the result?Charron
and what is reverse of 01?Emcee
@AngadSingh wouldn't 01 equivocate to 1? int a = 01; System.out.println(a); // prints 1Virtues
@AmareshJana if the reversedNum is an int then at last step multiplying 964632435 by 10 would result in int overflow. And you wouldn't get the expected answer. In java int is of 32 bits and ranges from -2,147,483,648 to +2,147,483,647.Anticipation
P
124

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.

Penult answered 26/1, 2011 at 19:8 Comment(7)
In practice you would convert to a string and reverse it, but of course integer to string conversion happens exactly like thisHeracliteanism
Link is broken!Yonita
Why is it that you use long, only to return an int? Does it have to do with division accuracy?Sommelier
You must use a long because if you pass in Integer.MAX_VALUE then multiplying that times 10 will wrap around thus ruining the algorithm. The long datatype gives you some space to do the work while you flip things around then collapsing it back down to an integer. The fact you have to ask this is the spirit of why this question is asked at interviews. It means you want to be a reader and writer of code, but when faced with reading code or writing code, you draw a blank and have to ask someone nicely on the internet to spoon feed you.Penult
this should be the accepted answer. Brilliant thank youCaphaitien
This was a popular programmer interview question from 2005 to 2010 and after the 3rd time I was asked this in an official setting, I figured I should solve it once and for all. I didn't think it would blow up like this. It's mostly a hazing question anyhow because programmers rarely or never have to do bit-shifting work close to the metal like this. One theory is that programmers who coded before 2005 thought bitshifting was holy grail, so it's a way to find out if you're a programmer who has been coding for over 15 years. A hallmark of a great coder is 10 years of daily practice.Penult
Accept this answer, user two-hundred and thirty-six thousand, five hundred and one! @VowelizeBerkeleianism
N
35

I am not clear about your Odd number. The way this code works is (it is not a Java specific algorithm) Eg. input =2345 first time in the while loop rev=5 input=234 second time rev=5*10+4=54 input=23 third time rev=54*10+3 input=2 fourth time rev=543*10+2 input=0

So the reversed number is 5432. If you just want only the odd numbers in the reversed number then. The code is:

while (input != 0) {    
    last_digit = input % 10;
    if (last_digit % 2 != 0) {     
        reversedNum = reversedNum * 10 + last_digit;

    }
    input = input / 10; 
}
Nord answered 27/9, 2010 at 17:21 Comment(6)
theres a mistake in your code. It should be reversedNum = reversedNum * 10 + input % 10;Goddart
Now it is proper I assume. The input=input/10 will take care and there will be no infinite loop.Nord
if the input is 1534236469 then what is the result?Charron
and what is reverse of 01?Emcee
@AngadSingh wouldn't 01 equivocate to 1? int a = 01; System.out.println(a); // prints 1Virtues
@AmareshJana if the reversedNum is an int then at last step multiplying 964632435 by 10 would result in int overflow. And you wouldn't get the expected answer. In java int is of 32 bits and ranges from -2,147,483,648 to +2,147,483,647.Anticipation
K
15

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.

Kingsize answered 24/3, 2014 at 12:45 Comment(0)
F
10
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

Froward answered 12/7, 2013 at 22:34 Comment(0)
S
5

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);
Selfrespect answered 5/6, 2018 at 5:18 Comment(2)
There is a loop internally within sb.reverse()Syphilis
You are right @Syphilis I have written a simple method to get the resultSelfrespect
C
4
int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());
Cyclonite answered 10/8, 2017 at 14:44 Comment(1)
adding "" is necessary , otherwise StringBuilder generates an empty output even when the documentation says that the constructor accepts an integer valueStheno
I
3
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;
    }
}
Idalla answered 21/7, 2013 at 10:29 Comment(0)
S
3

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);
Scourge answered 17/6, 2018 at 16:25 Comment(0)
B
2
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

Bradwell answered 21/2, 2014 at 11:12 Comment(1)
Its better if you provide explanation of code as well along with reasons what are the additional points you are covering here which have not been covered so far.Infelicity
V
2

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;
}
Vladamar answered 17/10, 2016 at 15:27 Comment(1)
Your range is wrong, 2147483647 would result in an output of 7463847412, an overflow. The actual set of numbers that are/aren't allowed is much more complicated.Scotland
H
1
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;
}
Horaciohorae answered 21/7, 2014 at 16:32 Comment(0)
F
1
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);
}
}
Fix answered 28/6, 2017 at 19:16 Comment(0)
Q
1

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;
}
Quintuplet answered 29/5, 2019 at 8:41 Comment(0)
P
1
    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
            
             }
Palliative answered 21/2, 2021 at 17:40 Comment(1)
I think you should put some explanation above your code, as the question is about the explanation about the methods that you have suggested in your answerRollo
B
0
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));

    }
Butterfield answered 3/7, 2013 at 8:18 Comment(0)
I
0

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");
Interminable answered 11/10, 2014 at 5:16 Comment(0)
T
0

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);
}
Travancore answered 20/6, 2015 at 20:25 Comment(0)
C
0

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;
}
Charron answered 25/9, 2015 at 7:43 Comment(0)
C
0

This is the shortest code to reverse an integer

int i=5263; 
System.out.println(Integer.parseInt(new StringBuffer(String.valueOf(i) ).reverse().toString()));
Carrollcarronade answered 3/12, 2015 at 14:21 Comment(1)
while(n!=0){r=r*10+n%10;n/=10;} //even shorter.Exophthalmos
P
0

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);
    }
}
Preexist answered 1/10, 2016 at 17:55 Comment(1)
Make it shorter public int reverse(int n) { return n < 10 ? n : (n % 10) * powerN.andThen(ten2powerN).apply(n) + reverse(n / 10); }Preexist
U
0

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;
    }
Uproar answered 3/2, 2017 at 18:30 Comment(1)
While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem.Andrel
D
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.

Daugava answered 16/3, 2017 at 14:36 Comment(0)
A
0

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.

Admiration answered 6/5, 2017 at 12:29 Comment(0)
K
0

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);

    }
Kevon answered 14/5, 2018 at 21:39 Comment(0)
L
0

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();
    }
}
Lemcke answered 1/6, 2018 at 10:17 Comment(2)
You should follow the Java Naming Conventions: method names always start with lowercase.Edmundson
Yup, sorry sir.Lemcke
Q
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

Quite answered 17/6, 2018 at 16:8 Comment(0)
P
0

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);
Pounce answered 3/10, 2018 at 8:32 Comment(0)
C
0
 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();
}
Complicacy answered 18/5, 2020 at 3:2 Comment(1)
The string builder contains an array of strings. But the question was how to do it without an array. And btw try / catch is really heavy operation and should be avoided where possibleExpletive
B
0
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;
        }
    }
}
Bushranger answered 19/1, 2021 at 13:14 Comment(1)
This question already contains multiple answers and an accepted answer. Can you explain (by editing your answer) where your answer differs from the other answers? Also know that Code-only answers are not useful in the long run.Scansion
C
0
public class JavaReverseNumbers {
public static void main(String args[]) {

    Scanner keyboard = new Scanner(System.in);

    String input;

    long remainder,inputlength,counter = 1;
    System.out.println("Enter a number: ");
    input = keyboard.next();
    long i = Integer.parseInt(input); 
    inputlength = input.length();
    
    while (counter <= inputlength){
        remainder = i % 10;
        i  = i / 10;
        System.out.print(remainder);
        counter++;
    }
}}
    

I'm new to this program, sorry for my mistakes. Here I used a conversion from String type to int type

Correlation answered 31/3, 2024 at 11:1 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Deciduous
D
-1

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);
    }
}
Dynamotor answered 9/3, 2015 at 11:39 Comment(2)
That works but I think the questioner wanted a solution that didn't involve strings.Soracco
ohhh yes!sorry i didn't see itDynamotor
P
-1
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;
}
Ponder answered 15/7, 2015 at 3:16 Comment(0)
F
-1
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.

Fortney answered 13/11, 2015 at 1:27 Comment(1)
While this code may answer the question, it would be better to explain how it solves the problem without introducing others and why to use it. Code-only answers are not useful in the long run.Cultism
S
-1
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);

    }
}
Sorcha answered 14/12, 2015 at 6:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.