Java reverse an int value without using array

178,564

Solution 1

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

Solution 2

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.

Solution 3

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.

Solution 4

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

Solution 5

int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());
Share:
178,564
user236501
Author by

user236501

Updated on November 23, 2021

Comments

  • user236501
    user236501 over 2 years

    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.

  • Rishav Dry
    Rishav Dry almost 14 years
    theres a mistake in your code. It should be reversedNum = reversedNum * 10 + input % 10;
  • sheki
    sheki almost 14 years
    Now it is proper I assume. The input=input/10 will take care and there will be no infinite loop.
  • g2server
    g2server over 9 years
    That works but I think the questioner wanted a solution that didn't involve strings.
  • C.A
    C.A over 9 years
    ohhh yes!sorry i didn't see it
  • Amaresh Jana
    Amaresh Jana almost 9 years
    if the input is 1534236469 then what is the result?
  • JAL
    JAL over 8 years
    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.
  • Denham Coote
    Denham Coote over 8 years
    while(n!=0){r=r*10+n%10;n/=10;} //even shorter.
  • nick w.
    nick w. over 7 years
    Make it shorter public int reverse(int n) { return n < 10 ? n : (n % 10) * powerN.andThen(ten2powerN).apply(n) + reverse(n / 10); }
  • Angad Singh
    Angad Singh over 7 years
    and what is reverse of 01?
  • user2977578
    user2977578 over 7 years
    @AngadSingh wouldn't 01 equivocate to 1? int a = 01; System.out.println(a); // prints 1
  • Joe C
    Joe C over 7 years
    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.
  • Ashish Kumar
    Ashish Kumar over 7 years
    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.
  • Cruncher
    Cruncher over 7 years
    In practice you would convert to a string and reverse it, but of course integer to string conversion happens exactly like this
  • RBz
    RBz about 7 years
    Link is broken!
  • Brydon Gibson
    Brydon Gibson about 7 years
    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.
  • Ghoti and Chips
    Ghoti and Chips over 6 years
    Why is it that you use long, only to return an int? Does it have to do with division accuracy?
  • Eric Leschinski
    Eric Leschinski over 6 years
    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.
  • Metin Dagcilar
    Metin Dagcilar over 6 years
    this should be the accepted answer. Brilliant thank you
  • Eric Leschinski
    Eric Leschinski about 6 years
    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.
  • wild_nothing
    wild_nothing over 5 years
    Accept this answer, user two-hundred and thirty-six thousand, five hundred and one! @user236501
  • MC Emperor
    MC Emperor over 5 years
    You should follow the Java Naming Conventions: method names always start with lowercase.
  • Jay Dangar
    Jay Dangar over 5 years
    Yup, sorry sir.
  • Anurag Sidana
    Anurag Sidana almost 5 years
    @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.
  • Steephen
    Steephen over 3 years
    There is a loop internally within sb.reverse()
  • 7uc1f3r
    7uc1f3r over 3 years
    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.
  • Ali Tamoor
    Ali Tamoor over 3 years
    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 answer
  • Anvita Shukla
    Anvita Shukla over 3 years
    adding "" is necessary , otherwise StringBuilder generates an empty output even when the documentation says that the constructor accepts an integer value
  • bhargav kumar gunda
    bhargav kumar gunda about 3 years
    You are right @Steephen I have written a simple method to get the result
  • Konstantin
    Konstantin over 2 years
    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 possible