Java reverse an int value without using array
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
Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4
Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50
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());
user236501
Updated on November 23, 2021Comments
-
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 almost 14 yearstheres a mistake in your code. It should be
reversedNum = reversedNum * 10 + input % 10;
-
sheki almost 14 yearsNow it is proper I assume. The input=input/10 will take care and there will be no infinite loop.
-
g2server over 9 yearsThat works but I think the questioner wanted a solution that didn't involve strings.
-
C.A over 9 yearsohhh yes!sorry i didn't see it
-
Amaresh Jana almost 9 yearsif the input is 1534236469 then what is the result?
-
JAL over 8 yearsWhile 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 over 8 yearswhile(n!=0){r=r*10+n%10;n/=10;} //even shorter.
-
nick w. over 7 yearsMake it shorter public int reverse(int n) { return n < 10 ? n : (n % 10) * powerN.andThen(ten2powerN).apply(n) + reverse(n / 10); }
-
Angad Singh over 7 yearsand what is reverse of 01?
-
user2977578 over 7 years@AngadSingh wouldn't 01 equivocate to 1? int a = 01; System.out.println(a); // prints 1
-
Joe C over 7 yearsWhile 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 over 7 yearsIts 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 over 7 yearsIn practice you would convert to a string and reverse it, but of course integer to string conversion happens exactly like this
-
RBz about 7 yearsLink is broken!
-
Brydon Gibson about 7 yearsYour range is wrong,
2147483647
would result in an output of7463847412
, an overflow. The actual set of numbers that are/aren't allowed is much more complicated. -
Ghoti and Chips over 6 yearsWhy is it that you use
long
, only to return an int? Does it have to do with division accuracy? -
Eric Leschinski over 6 yearsYou 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 over 6 yearsthis should be the accepted answer. Brilliant thank you
-
Eric Leschinski about 6 yearsThis 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 over 5 yearsAccept this answer, user two-hundred and thirty-six thousand, five hundred and one! @user236501
-
MC Emperor over 5 yearsYou should follow the Java Naming Conventions: method names always start with lowercase.
-
Jay Dangar over 5 yearsYup, sorry sir.
-
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 over 3 yearsThere is a loop internally within
sb.reverse()
-
7uc1f3r over 3 yearsThis 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 over 3 yearsI 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 over 3 yearsadding "" is necessary , otherwise StringBuilder generates an empty output even when the documentation says that the constructor accepts an integer value
-
bhargav kumar gunda about 3 yearsYou are right @Steephen I have written a simple method to get the result
-
Konstantin over 2 yearsThe 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