Can anyone explain to me how to reverse a number start with zero in java. I trying to reverse a number 025 but output is only 52. But output should be 520 explanation much appreciated.
-
3please provide your code and what you tried so far– deterministicFailMar 30, 2015 at 7:45
-
4Numeric reversal, I think, is mostly a string operation...– npintiMar 30, 2015 at 7:46
-
3Why shouldn't it output 520000? After all, 025 and 000025 are the same number.– user253751Mar 30, 2015 at 7:47
-
What is "an integer with zero"? I use positive integers for counting the number of sheep in my field. I know what 25 sheep look like, but what would 025 sheep look like?– Dawood ibn KareemMar 30, 2015 at 7:53
-
1@Sutanu: I think you should leave here your original wording with integer - thus your question will remain useful for future readers with the same initial understanding. Please read my answer below, follow the link to Oracle tutorial and implement the solution on your own - thus you will fulfil the intention of StackOVerflow.– Honza ZidekMar 30, 2015 at 8:14
1 Answer
You are mixing types. "025" is not a number, it's a String
. In a number you simply cannot distinguish between 25, 025, 0025, 00025, ... Implement your assignment as a String operation.
public String reverseString(String s) {
// put your code here
}
You may find very useful the Oracle tutorial on Strings here: https://docs.oracle.com/javase/tutorial/java/data/strings.html
-
This is almost a good answer IMO; but you need to deal with a negative sign. Mar 30, 2015 at 8:06
-
@Bathsheba: my answer does not prevent dealing with negative sign - it is the part
//put your code here
where it may be implemented :) However, until it is defined in the specification I would not be sure what the expected output should be. Should"-025"
convert to"-520"
,"520-"
or is such an input not to be expected at all? :) Mar 30, 2015 at 8:10 -
The Apache Commons
StringUtils
class has areverse
method. Mar 30, 2015 at 11:01 -
No. An important part of professional computer programming is knowing when to write your own method, and when to use one that somebody else has already written and tested. This is a clear case of the latter. Mar 30, 2015 at 11:10
-
Well, in 20 years of programming, I've seen loads and loads of programmers write methods for themselves that they shouldn't have. I really believe that "don't re-invent the wheel" should be one of the first lessons that every programmer should learn. What you're doing here is specifically instructing the OP to re-invent his own wheels, and the opposite lesson is what's needed here. Mar 30, 2015 at 18:42